国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python下線程之間的共享和釋放示例

2019-11-25 17:33:45
字體:
來源:轉載
供稿:網友

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

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)

總結

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桦南县| 潞西市| 澄城县| 长葛市| 贞丰县| 萨嘎县| 乳山市| 江山市| 吴旗县| 高阳县| 安阳县| 崇礼县| 皋兰县| 景宁| 宁波市| 宁阳县| 无极县| 贵定县| 彭州市| 合肥市| 岱山县| 左云县| 长岛县| 颍上县| 裕民县| 怀柔区| 财经| 盐山县| 阿拉善右旗| 大兴区| 浦江县| 兴和县| 黎城县| 舟曲县| 西乡县| 石台县| 云梦县| 竹北市| 霞浦县| 鄂尔多斯市| 兴仁县|