python 类变量 在多线程下的共享与释放问题

最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大

1.python 类变量 在多线程情况 下的 是共享的

2.python 类变量 在多线程情况 下的 释放是不完全的

3.python 类变量 在多线程情况 下没释放的那部分 内存 是可以重复利用的

 1 import threading
 2 import time
 3 
 4 class Test:
 5 
 6     cache = {}
 7     
 8     @classmethod
 9     def get_value(self, key):
10         value = Test.cache.get(key, [])
11         return len(value)
12 
13     @classmethod
14     def store_value(self, key, value):
15         if not Test.cache.has_key(key):
16             Test.cache[key] = range(value)
17         else:
18             Test.cache[key].extend(range(value)) 
19         return len(Test.cache[key])
20 
21     @classmethod
22     def release_value(self, key):
23         if Test.cache.has_key(key):
24             Test.cache.pop(key)
25         return True
26 
27     @classmethod
28     def print_cache(self):
29         print 'print_cache:'
30         for key in Test.cache:
31             print 'key: %d, value:%d' % (key, len(Test.cache[key]))
32 
33 def worker(number, value):
34     key = number % 5
35     print 'threading: %d, store_value: %d' % (number, Test.store_value(key, value))
36     time.sleep(10)
37     print 'threading: %d, release_value: %s' % (number, Test.release_value(key))
38 
39 if __name__ == '__main__':
40     thread_num = 10
41     
42     thread_pool = []
43     for i in range(thread_num):
44         th = threading.Thread(target=worker,args=[i, 1000000])
45         thread_pool.append(th)
46         thread_pool[i].start()
47 
48     for thread in thread_pool:
49         threading.Thread.join(thread)
50     
51     Test.print_cache()
52     time.sleep(10)
53     
54     thread_pool = []
55     for i in range(thread_num):
56         th = threading.Thread(target=worker,args=[i, 100000])
57         thread_pool.append(th)
58         thread_pool[i].start()
59 
60     for thread in thread_pool:
61         threading.Thread.join(thread)
62     
63     Test.print_cache()
64     time.sleep(10)

总结

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

原文地址:https://www.cnblogs.com/2010Freeze/p/3162658.html