黑松山资源网 Design By www.paidiu.com
最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大
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)
总结
公用的数据,除非是只读的,不然不要当类成员变量,一是会共享,二是不好释放。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神手游】5.1版本更新维护预告
- 李锦华.1987-日与夜(LP版)【SOLO】【WAV+CUE】
- 伍珂玥.2014-伍珂玥【湾彩星辰】【FLAC分轨】
- 吕方.2001-旧情人·老情歌精选2CD【华纳】【WAV+CUE】
- 《星际战士2》¥219,《100% 鲜橙汁》¥7
- 手办鉴赏室:少女眼神颇有杀意!连衣裙勾勒傲人轮廓
- 未来可期的二次元大逃杀游戏——《白厄战境》简评
- 炉石传说死亡骑士卡组怎么搭配 死亡骑士最新卡组2024推荐
- 魔兽世界地下堡珍玩怎么升级 地下堡珍玩升级方法攻略分享
- 魔兽世界怎么获得泽克维尔的残血珍玩 泽克维尔的残血珍玩获取方式
- FrankSinatra-StrangersInTheNight(1966Jazz)[Flac24-96]
- 大原樱子《CAMON+5thAnniversaryBest~》2CD[24-96]flac
- Isgaard2003-GoldenKey(LimitedEdition)【WAV+CUE】
- 《合金装备3RE》伊娃定妆照公布:没被政确太好了
- 石家庄新增《黑神话:悟空》墙绘:小狐狸萍萍