Recently was a multi-threaded to the pit, did not realize that class variables are shared under multi-threaded, there is not aware of the memory release problem, resulting in the more tired the greater
1.python class variables are shared in multi-threaded situations
The release of 2.python class variables in multithreaded situations is incomplete
3.python class variables The portion of memory that is not released in multithreaded situations can be reused
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 () print ' threading:%d, Release_value:%s '% (number, test.release_value (key)) if __name __ = = ' __main__ ': Thread_num = 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 the thread in Thread_pool:threading. Thread.Join (thread) Test.print_cache () Time.sleep (Ten) 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 the thread in Thread_pool:threading. Thread.Join (thread) Test.print_cache () Time.sleep (10)
Public data, unless it is read-only, or not as a class member variable, one will be shared, and the second is not good to release.