最近被多線程給坑了下,沒意識到類變量在多線程下是共享的,還有一個就是沒意識到 內存釋放問題,致使越累越大python
1.python 類變量 在多線程狀況 下的 是共享的多線程
2.python 類變量 在多線程狀況 下的 釋放是不徹底的app
3.python 類變量 在多線程狀況 下沒釋放的那部分 內存 是能夠重複利用的spa
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)
總結線程
公用的數據,除非是隻讀的,否則不要當類成員變量,一是會共享,二是很差釋放。code