当前第2页 返回上一页
加锁后的正确代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import threading
import time
count = 0
lock = threading.Lock()
class Counter(threading.Thread):
def __init__( self , name):
self .thread_name = name
self .lock = threading.Lock()
super (Counter, self ).__init__(name = name)
def run( self ):
global count
global lock
for i in xrange ( 100000 ):
lock.acquire()
count = count + 1
lock.release()
counters = [Counter( 'thread:%s' % i) for i in range ( 5 )]
for counter in counters:
counter.start()
time.sleep( 5 )
print 'count=%s' % count
|
结果:
count=500000
注意锁的全局性
这是一个简单的Python语法问题,但在逻辑复杂时有可能被忽略.
要保证锁对于多个子线程来说是共用的,即不要在Thread的子类内部创建锁.
以下为错误代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import threading
import time
count = 0
class Counter(threading.Thread):
def __init__( self , name):
self .thread_name = name
self .lock = threading.Lock()
super (Counter, self ).__init__(name = name)
def run( self ):
global count
for i in xrange ( 100000 ):
self .lock.acquire()
count = count + 1
self .lock.release()
counters = [Counter( 'thread:%s' % i) for i in range ( 5 )]
for counter in counters:
print counter.thread_name
counter.start()
time.sleep( 5 )
print 'count=%s' % count
|
相关推荐:
python线程中同步锁详解
python多线程之事件Event的使用详解
python线程池threadpool的实现
以上就是Python多线程中阻塞(join)与锁(Lock)使用误区解析的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python生成任意范围任意精度的随机数的方法
Python中for循环与range()函数的简单介绍(附示例)
Python3怎么安装库
Python闭包是什么?Python闭包的简单介绍(附示例)
Python可变类型和不可变类型区别
Python中encoding是什么意思
Python中raise 与 raise ... from之间有何区别?
什么是Python线程模块?九种方法助你了解线程模块
Python去除扩展名
【Python学习】pycharm超实用使用教程
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python多线程中阻塞(join)与锁(Lock)使用误区解析