マルチスレッド下での Python クラス変数の問題の共有と解放

高洛峰
リリース: 2016-10-18 10:32:20
オリジナル
1157 人が閲覧しました

最近マルチスレッドに騙されました、マルチスレッドではクラス変数が共有されるということを知らなかったので、さらに疲れました。マルチスレッド状況でのクラス変数 以下は共有されています

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 学習者の迅速な成長を支援します!