提问人:Deltag0ny 提问时间:10/26/2022 更新时间:10/26/2022 访问量:51
使用锁而不是事件?
Using locks instead of events?
问:
所以我在学习线程,看到锁是用来同步线程的。但是,我不明白为什么使用锁定而不是触发事件会更有利。
在这个示例中,我通过触发事件使第一个线程在第二个线程之后完成。有没有办法使用锁来达到相同的结果,它是否更有效率?
from threading import *
import time
list1 = []
def computation():
print('Starting computation')
global list1
for x in range(100000000):
list1.append(x)
if t2 == True: #Making it give me a "result" after the other thread if it would need data from it, for example.
print('End of computation')
def Background_work(x, lock):
with lock:
for x in range(x):
print('...')
time.sleep(2)
return True
if __name__ == '__main__':
lock = Lock()
t1 = Thread(target = computation)
t2 = Thread(target = Background_work, args = (5, lock))
t1.start()
t2.start()
t1.join()
t2.join()
print('All tasks completed')
我还包含了一个无用的锁定,因为我不明白为什么这段代码没有给出相同的结果:Background_work()
list1 = []
def computation():
print('Starting computation')
global list1
for x in range(100000000):
list1.append(x)
time.sleep(0.01)
print('End of computation')
def Background_work(x, lock):
with lock:
for x in range(x):
print('...')
time.sleep(2)
t1 = Thread(target = computation)
t2 = Thread(target = Background_work, args = (5, lock))
t1.start()
t2.start()
我以为第一个线程会一直运行,直到它到达,此时第二个线程的锁会让它等到自己完成,因为第一个线程正在休眠。time.sleep()
答: 暂无答案
评论
t2 == True
True
t2
t1
t2
t1
t2
t1
t1
.appending