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

yipeiwu_com6年前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)

总结

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

相关文章

PyQt QCombobox设置行高的方法

之前在网上查找了很多相关资料,有说设置icon高度来支持item的,有说要添加自己写指定高度的view来填充的,但是对于一个只有文字的Qcombobox来说,这些无疑是太过繁琐了。研究了...

pip安装python库的方法总结

使用pip安装python库的几种方式 1、使用pip在线安装 1.1 安装单个package 格式如下: pip install SomePackage 示例如下: 比如:pip...

Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享

Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享

支付宝十年账单上的数字有点吓人,但它统计的项目太多,只是想看看到底单纯在淘宝上支出了多少,于是写了段脚本,统计任意时间段淘宝订单的消费情况,看那结果其实在淘宝上我还是相当节约的说。 脚本...

Python常用的内置序列结构(列表、元组、字典)学习笔记

列表与元组 列表用大括号[]表示,元组用圆括号()表示。 列表可以修改,字符串与元组不可修改。 元组的分片还是元组,列表的分片还是列表。 1.列表方法: name=["zhang3"...

浅谈Python中列表生成式和生成器的区别

列表生成式语法: [x*x for x in range(0,10)] //列表生成式,这里是中括号 //结果 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81...