python类变量共享吗_python 类变量在多线程下共享与释放问题

对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大

1.python 类变量 在多线程情况 下的 是共享的

2.python 类变量 在多线程情况 下的 释放是不完全的

3.python 类变量 在多线程情况 下没释放的那部分 内存 是可以重复利用的

# @param python 类变量 在多线程下的共享与释放问题

# @author 编程之家 jb51.cc|www.jb51.cc

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,100000])

thread_pool.append(th)

thread_pool[i].start()

for thread in thread_pool:

threading.Thread.join(thread)

Test.print_cache()

time.sleep(10)

# End www.jb51.cc

总结

公用的数据,除非是只读的,不然不要当类成员变量,一是会共享,二是不好释放。

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值