当前第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
Python入门:Python的环境搭建(ide)工具
Python如何实现爬取需要登录的网站代码实例
Python中元类与枚举类的介绍(代码示例)
Python具体做些什么
Python之post登录实例代码
Python装饰器-限制函数调用次数的方法(10s调用一次)
怎么查看Python是否安装好
如何在Python中添加自定义模块的方法介绍
Python中如何django使用haystack:全文检索的框架的实例讲解
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python多线程中阻塞(join)与锁(Lock)使用误区解析