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

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

总结

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

相关文章

python3.6.3安装图文教程 TensorFlow安装配置方法

python3.6.3安装图文教程 TensorFlow安装配置方法

本文主要介绍Python3.6及TensorFlow的安装和配置流程。 一、Python官网下载自己电脑和系统对应的Python安装包。  网址:下载地址 一直往下拉到Fil...

python根据时间获取周数代码实例

时间 时间和周数 import time import datetime # 获取今天是第几周 print(time.strftime('%W')) # 获取当前是周几(0-6,0...

python中的for循环

python中的for循环

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。 语法: for循环的语法格式如下: for iterating_var in sequence:...

python实现计数排序与桶排序实例代码

python实现计数排序与桶排序实例代码

计数排序 找到给定序列的最小值与最大值 创建一个长度为最大值-最小值+1的数组,初始化都为0 然后遍历原序列,并为数组中索引为当前值-最小值的值+1 此时数组中已经记录...

Python合并两个字典的常用方法与效率比较

本文实例讲述了Python合并两个字典的常用方法与效率比较。分享给大家供大家参考。具体分析如下: 下面的代码举例了5种合并两个字典的方法,并且做了个简单的性能测试 #!/usr/bi...