gpt4 book ai didi

Python 线程。如何锁定线程?

转载 作者:IT老高 更新时间:2023-10-28 20:26:20 25 4
gpt4 key购买 nike

我正在尝试了解线程和并发的基础知识。我想要一个简单的案例,两个线程反复尝试访问一个共享资源。

代码:

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'被释放。

运行清楚地表明情况并非如此。您将获得所有随机数据竞赛增量。

锁对象到底是怎么用的?

此外,我尝试将锁放在线程函数中,但仍然没有成功。

最佳答案

您可以看到,您的锁在您使用它们时几乎可以正常工作,如果您放慢进程并让它们阻塞更多。你有正确的想法,用锁包围关键的代码片段。这是对您的示例的一个小调整,以向您展示每个人如何等待另一个人释放锁定。

import threading
import time
import inspect

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 incre():
global count
caller = inspect.getouterframes(inspect.currentframe())[1][3]
print "Inside %s()" % caller
print "Acquiring lock"
with lock:
print "Lock Acquired"
count += 1
time.sleep(2)

def bye():
while count < 5:
incre()

def hello_there():
while count < 5:
incre()

def main():
hello = Thread(hello_there)
goodbye = Thread(bye)


if __name__ == '__main__':
main()

样本输出:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

关于Python 线程。如何锁定线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com