全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
782 0
2020-10-28
CDA人工智能学院致力于以优质的人工智能在线教育资源助力学员的DT职业梦想!课程内容涵盖数据分析机器学习深度学习人工智能tensorFlowPyTorch知识图谱等众多核心技术及行业案例,让每一个学员都可以在线灵活学习,快速掌握AI时代的前沿技术。PS:私信我即可获取CDA会员1个月免费试听机会
最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大
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.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.start()
   
   for thread in thread_pool:
     threading.Thread.join(thread)
     
   Test.print_cache()
   time.sleep(10)
总结
公用的数据,除非是只读的,不然不要当类成员变量,一是会共享,二是不好释放。

0D04CBB8996CB009643B8D6FD844F0C0.jpg


关注“CDA人工智能学院”,回复“录播”获取更多人工智能精选直播视频!


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群