Python下線程之間的共享和釋放示例
最近被多線程給坑了下,沒意識到類變量在多線程下是共享的,還有一個(gè)就是沒意識到 內(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)類成員變量,一是會共享,二是不好釋放。
相關(guān)文章
matplotlib繪制正余弦曲線圖的實(shí)現(xiàn)
這篇文章主要介紹了matplotlib繪制正余弦曲線圖的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
Python基于OpenCV實(shí)現(xiàn)人臉檢測并保存
這篇文章主要介紹了Python基于OpenCV實(shí)現(xiàn)人臉檢測并保存,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
python實(shí)現(xiàn)圖像增強(qiáng)算法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)圖像增強(qiáng)算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
Python Numpy教程之排序,搜索和計(jì)數(shù)詳解
這篇文章主要為大家詳細(xì)介紹了Python?NumPy中排序,搜索和計(jì)數(shù)的實(shí)現(xiàn),文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Python有一定幫助,需要的可以參考一下2022-08-08
Python?Pandas實(shí)現(xiàn)將字符串格式轉(zhuǎn)為日期時(shí)間格式
日期和時(shí)間數(shù)據(jù)在數(shù)據(jù)分析和處理中起著關(guān)鍵作用,本文將詳細(xì)介紹如何使用Pandas將字符串格式的日期時(shí)間數(shù)據(jù)轉(zhuǎn)換為日期時(shí)間格式,需要的可以參考下2024-01-01
python實(shí)戰(zhàn)之用emoji表情生成文字
這篇文章主要介紹了python實(shí)戰(zhàn)之用emoji表情生成文字,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05

