Python下線程之間的共享和釋放示例
最近被多線程給坑了下,沒(méi)意識(shí)到類變量在多線程下是共享的,還有一個(gè)就是沒(méi)意識(shí)到 內(nèi)存釋放問(wèn)題,導(dǎo)致越累越大
1.python 類變量 在多線程情況 下的 是共享的
2.python 類變量 在多線程情況 下的 釋放是不完全的
3.python 類變量 在多線程情況 下沒(méi)釋放的那部分 內(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)類成員變量,一是會(huì)共享,二是不好釋放。
相關(guān)文章
基于Python實(shí)現(xiàn)敲擊木魚積累功德效果
最近大家都很流行用手機(jī)敲擊電子木魚積累功德,這在很多短視頻中也常常見到。本文將用Python語(yǔ)言實(shí)現(xiàn)這一效果,感興趣的小伙伴開業(yè)了解一下2022-11-11
Python實(shí)現(xiàn)二維數(shù)組輸出為圖片
下面小編就為大家分享一篇Python實(shí)現(xiàn)二維數(shù)組輸出為圖片,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Python的pytest測(cè)試框架中fixture的使用詳解
這篇文章主要介紹了pytest中fixture的使用詳解,pytest是一個(gè)非常成熟的全功能的Python測(cè)試框架,能夠支持簡(jiǎn)單的單元測(cè)試和復(fù)雜的功能測(cè)試,還可以用來(lái)做selenium/appnium等自動(dòng)化測(cè)試、接口自動(dòng)化測(cè)試,需要的朋友可以參考下2023-07-07
Python while循環(huán)使用else語(yǔ)句代碼實(shí)例
這篇文章主要介紹了Python while循環(huán)使用else語(yǔ)句代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02

