多线程4
多线程4
为了等待线程执行完毕,除了多线程2中提到的join,还可以使用本文的lock。
以下代码展示未使用lock的情况:
import threading
def thread1_job():
global A
for i in range(10):
A += 1
print('thread1', A)
def thread2_job():
global A
for i in range(10):
A += 10
print('thread2', A)
if __name__ == '__main__':
A = 0
t1 = threading.Thread(target=thread1_job)
t2 = threading.Thread(target=thread2_job)
t1.start()
t2.start()
输出结果:
thread1 1
thread1 2
thread1 3
thread1 4
thread2thread1 14
thread2 25
15
thread1 26
thread1 27
thread1 thread228
thread138
thread2 39
49
thread2thread1 60
59
thread2 70
thread2 80
thread2 90
thread2 100
thread2 110
thread1和thread2同时对global变量A进行操作,表现为交替对A+1或者+10。
如果我们想要等thread1执行完再执行其他步骤,那就可以用上lock:
import threading
def thread1_job():
global A, lock
lock.acquire()
for i in range(10):
A += 1
print('thread1', A)
lock.release()
def thread2_job():
global A
for i in range(10):
A += 10
print('thread2', A)
if __name__ == '__main__':
A = 0
lock = threading.Lock()
t1 = threading.Thread(target=thread1_job)
t2 = threading.Thread(target=thread2_job)
t1.start()
t2.start()
输出结果:
thread1 1
thread1 2
thread1 3
thread1 4
thread1 5
thread1 6
thread1 7
thread1 8
thread1 9
thread1 10
thread2 20
thread2 30
thread2 40
thread2 50
thread2 60
thread2 70
thread2 80
thread2 90
thread2 100
thread2 110
此时lock的acquire和release之间的任务执行完毕后,才执行其他任务。