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)

总结

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

相关文章

让代码变得更易维护的7个Python库

随着软件项目进入“维护模式”,对可读性和编码标准的要求很容易落空(甚至从一开始就没有建立过那些标准)。然而,在代码库中保持一致的代码风格和测试标准能够显著减轻维护的压力,也能确保新的开发...

Django ModelForm组件使用方法详解

Django ModelForm组件使用方法详解

一、创建ModelForm from django.forms import ModelForm from appxx import models from django.form...

python进阶教程之异常处理

在项目开发中,异常处理是不可或缺的。异常处理帮助人们debug,通过更加丰富的信息,让人们更容易找到bug的所在。异常处理还可以提高程序的容错性。 我们之前在讲循环对象的时候,曾提到一个...

windows下安装Python虚拟环境virtualenvwrapper-win

1、安装 执行命令 pip install virtualenv 为了使用virtualenv更方便,可以借助 virtualenvwrapper 执行命令 pip install vi...

Python3安装Scrapy的方法步骤

Python3安装Scrapy的方法步骤

本文介绍了Python3安装Scrapy的方法步骤,分享给大家,具体如下: 运行平台:Windows Python版本:Python3.x IDE:Sublime text...