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

首頁 > 編程 > Python > 正文

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

2020-02-23 01:04:29
字體:
供稿:網(wǎng)友

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

1.python 類變量 在多線程情況 下的 是共享的

2.python 類變量 在多線程情況 下的 釋放是不完全的

3.python 類變量 在多線程情況 下沒釋放的那部分 內(nèi)存 是可以重復(fù)利用的

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)

總結(jié)

公用的數(shù)據(jù),除非是只讀的,不然不要當(dāng)類成員變量,一是會共享,二是不好釋放。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 鹰潭市| 葫芦岛市| 宜阳县| 望江县| 阿拉善左旗| 长寿区| 霍州市| 万州区| 正宁县| 邵武市| 旬邑县| 甘肃省| 商水县| 吉安县| 红安县| 卢湾区| 贵德县| 岱山县| 库车县| 彰武县| 巴东县| 新竹县| 绥芬河市| 呈贡县| 湖南省| 镇平县| 思茅市| 大庆市| 龙泉市| 墨江| 定日县| 德兴市| 鄂托克旗| 衢州市| 满洲里市| 垫江县| 建水县| 兴业县| 乌苏市| 平顶山市| 贵德县|