【发布时间】:2012-05-09 22:44:33
【问题描述】:
我正在尝试了解线程和并发的基础知识。我想要一个简单的案例,两个线程反复尝试访问一个共享资源。
代码:
import threading
class Thread(threading.Thread):
def __init__(self, t, *args):
threading.Thread.__init__(self, target=t, args=args)
self.start()
count = 0
lock = threading.Lock()
def increment():
global count
lock.acquire()
try:
count += 1
finally:
lock.release()
def bye():
while True:
increment()
def hello_there():
while True:
increment()
def main():
hello = Thread(hello_there)
goodbye = Thread(bye)
while True:
print count
if __name__ == '__main__':
main()
所以,我有两个线程,都试图增加计数器。我认为如果线程'A'调用increment(),lock将被建立,阻止'B'访问直到'A'释放。
运行清楚地表明情况并非如此。您将获得所有随机数据竞赛增量。
锁对象到底是怎么用的?
此外,我尝试将锁放在线程函数中,但仍然没有成功。
【问题讨论】:
-
@Ignacio Vazquez-Abrams - 现在应该。我省略了
if __name__位。你说的是这个吗? -
它也不适合我。我希望您的线程创建看起来像:
hello = threading.Thread(target=hello_there),然后启动线程hello.start()。 -
你知道你可以使用
with lock:而不是lock.acquire(); try: ...; finally: lock.release()吗? -
另外,我不太明白你的问题。代码试图演示什么?
-
您正确使用了锁。是什么让你认为你不是?
标签: python multithreading