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)

總結

公用的數據,除非是只讀的,不然不要當類成員變量,一是會共享,二是不好釋放。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM