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)

总结

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

相关文章

Tensorflow 自带可视化Tensorboard使用方法(附项目代码)

Tensorflow 自带可视化Tensorboard使用方法(附项目代码)

Tensorboard: 如何更直观的观察数据在神经网络中的变化,或是已经构建的神经网络的结构。上一篇文章说到,可以使用matplotlib第三方可视化,来进行一定程度上的可视化。然而T...

python实现根据窗口标题调用窗口的方法

本文实例讲述了python实现根据窗口标题调用窗口的方法。分享给大家供大家参考。具体分析如下: 当你知道一个windows窗口的标题后,可以用下面的代码调用窗口,甚至向窗口内写入内容。...

深入浅析Python字符编码

Python的字符串编码规则一直让我很头疼,花了点时间研究了下,并不复杂。主要涉及的内容有常用的字符编码的特点,并介绍了在python2.x中如何与编码问题作战,本文关于Python的内...

Python生成rsa密钥对操作示例

本文实例讲述了Python生成rsa密钥对操作。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import rsa # 先生成一对密钥,然后保存....

Python中列表和元组的使用方法和区别详解

一、二者区别 列表: 1.可以增加列表内容 append 2.可以统计某个列表段在整个列表中出现的次数 count 3.可以插入一个字符串,并把整个字符串的每个字母拆分当作一个列...