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)

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

Posted in 未分类

发表评论