python 類別變數 在多執行緒下的共享與釋放問題

高洛峰
發布: 2016-10-18 10:32:20
原創
1157 人瀏覽過

最近被多線程給坑了下,沒意識到類變量在多線程下是共享的,還有一個就是沒意識到內存釋放問題,導致越累越大

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)
登入後複製

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!