国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 西宁市| 永定县| 栾川县| 葵青区| 林芝县| 乐业县| 城口县| 玉门市| 广河县| 甘孜| 福贡县| 杭锦后旗| 南澳县| 顺昌县| 金坛市| 治多县| 峨眉山市| 广丰县| 策勒县| 沁阳市| 灵武市| 阳高县| 上饶县| 东源县| 陆良县| 孟村| 星子县| 武汉市| 平邑县| 荣成市| 蒙城县| 凌源市| 吉木萨尔县| 习水县| 齐河县| 双流县| 许昌县| 威海市| 五原县| 珲春市| 象山县|