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)

总结

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

相关文章

PyQt5创建一个新窗口的实例

PyQt5创建一个新窗口的实例

1.使用Qt Design设计一个空白窗口(注意:我是使用MainWindow创建的窗口) 2.使用PyUIC将.ui文件转换成.py文件 右键.ui文件->External T...

详解python破解zip文件密码的方法

详解python破解zip文件密码的方法

1、单线程破解纯数字密码 注意: 不包括数字0开头的密码 import zipfile,time,sys start_time = time.time() def extract()...

Python lxml解析HTML并用xpath获取元素的方法

代码 使用方法见注释 #-*- coding: UTF-8 -*- from lxml import etree source = u''' <div><p c...

教女朋友学Python3(二)简单的输入输出及内置函数查看 原创

教女朋友学Python3(二)简单的输入输出及内置函数查看 原创

这是第二天了,工作之余和女朋友一起学Python3,代码都是她敲的,有点辣眼睛,仅做参考。 1.题目:输入“姓名”,输出“你好,姓名” 有关安装和打开Python shell的步骤,参考...

Python socket C/S结构的聊天室应用实现

Python socket C/S结构的聊天室应用 服务端: #!/usr/bin/env python #coding:utf8 import socket,select def...