首页 编程教程正文

Python下线程之间的共享和释放示例

piaodoo 编程教程 2020-02-02 12:20:47 876 0 python教程

这篇文章主要用示例简单介绍了Python下线程之间的共享和释放,线程一直是Python开发者中的热点问题,需要的朋友可以参考下

最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大

1.python 类变量 在多线程情况 下的 是共享的

2.python 类变量 在多线程情况 下的 释放是不完全的

3.python 类变量 在多线程情况 下没释放的那部分 内存 是可以重复利用的

import threading
 import time
  
 class Test:
  
   cache = {}
    
   @classmethod
   def get_value(self, key):
     value = Test.cache.get(key, [])
     return len(value)
  
   @classmethod
   def store_value(self, key, value):
     if not Test.cache.has_key(key):
       Test.cache[key] = range(value)
     else:
       Test.cache[key].extend(range(value))
     return len(Test.cache[key])
  
   @classmethod
   def release_value(self, key):
     if Test.cache.has_key(key):
       Test.cache.pop(key)
     return True
  
   @classmethod
   def print_cache(self):
     print 'print_cache:'
     for key in Test.cache:
       print 'key: %d, value:%d' % (key, len(Test.cache[key]))
  
 def worker(number, value):
   key = number % 5
   print 'threading: %d, store_value: %d' % (number, Test.store_value(key, value))
   time.sleep(10)
   print 'threading: %d, release_value: %s' % (number, Test.release_value(key))
  
 if __name__ == '__main__':
   thread_num = 10
    
   thread_pool = []
   for i in range(thread_num):
     th = threading.Thread(target=worker,args=[i, 1000000])
     thread_pool.append(th)
     thread_pool[i].start()
  
   for thread in thread_pool:
     threading.Thread.join(thread)
    
   Test.print_cache()
   time.sleep(10)
    
   thread_pool = []
   for i in range(thread_num):
     th = threading.Thread(target=worker,args=[i, 100000])
     thread_pool.append(th)
     thread_pool[i].start()
  
   for thread in thread_pool:
     threading.Thread.join(thread)
    
   Test.print_cache()
   time.sleep(10)

总结

公用的数据,除非是只读的,不然不要当类成员变量,一是会共享,二是不好释放。

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:https://www.piaodoo.com/986.html

评论

搜索