threading.join() 会阻塞调用它的线程吗?
does threading.join() block the thread that's called it?
基于https://docs.python.org/3/library/threading.html:
join() waits until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates
现在我有点困惑。考虑以下代码:
import threading
def count(start, end):
for i in range(start, end):
print(i)
t1 = threading.Thread(target=count, args=[10, 20])
t2 = threading.Thread(target=count, args=[30, 40])
t1.start()
t2.start()
t1.join()
t2.join()
输出:
10
11
12
30
31
32
33
34
35
36
37
38
39
13
14
15
16
17
18
19
t1.join() 在主线程中被调用。所以我认为主线程被阻塞并且 t2.join() 没有被调用。
在这种情况下,我希望在给定 t1 的范围内的任何数字之前不会看到给定给 t2 的范围内的任何数字。
那么为什么在19之前打印30呢?
您的程序在等待 t1 和 t2 完成之前启动了两个线程,这就是为什么您的控制台中在 19
之前有 30
。
当程序等待 t1 完成时,t2 仍然是 运行 并打印到控制台。
如果出于任何原因你想使用多线程并且 t2
在开始之前等待 t1
完成,你可以使用以下代码:
import threading
import time # Useful for adding some delay in order to visualize what is happening
def count(start, end):
for i in range(start, end):
print(i)
time.sleep(500) # Add some delay to see clearly what is happening
t1 = threading.Thread(target=count, args=[10, 20])
t2 = threading.Thread(target=count, args=[30, 40])
# This starts the two threads and wait for bot of them to finish
#t1.start()
#t2.start()
#
#t1.join()
#t2.join()
#
# This starts one thread and wait for it to finish before starting the other
t1.start()
t1.join() # We wait for t1 to finish
t2.start() # Then we start the second thread (t2)
t2.join()
注意:您不能启动同一个线程 2 次,因此如果您想同时使用 2 个线程 运行 测试代码,请确保 comment/delete 我的部分。
编辑:我所说的程序是指主线程
基于https://docs.python.org/3/library/threading.html:
join() waits until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates
现在我有点困惑。考虑以下代码:
import threading
def count(start, end):
for i in range(start, end):
print(i)
t1 = threading.Thread(target=count, args=[10, 20])
t2 = threading.Thread(target=count, args=[30, 40])
t1.start()
t2.start()
t1.join()
t2.join()
输出:
10
11
12
30
31
32
33
34
35
36
37
38
39
13
14
15
16
17
18
19
t1.join() 在主线程中被调用。所以我认为主线程被阻塞并且 t2.join() 没有被调用。 在这种情况下,我希望在给定 t1 的范围内的任何数字之前不会看到给定给 t2 的范围内的任何数字。 那么为什么在19之前打印30呢?
您的程序在等待 t1 和 t2 完成之前启动了两个线程,这就是为什么您的控制台中在 19
之前有 30
。
当程序等待 t1 完成时,t2 仍然是 运行 并打印到控制台。
如果出于任何原因你想使用多线程并且 t2
在开始之前等待 t1
完成,你可以使用以下代码:
import threading
import time # Useful for adding some delay in order to visualize what is happening
def count(start, end):
for i in range(start, end):
print(i)
time.sleep(500) # Add some delay to see clearly what is happening
t1 = threading.Thread(target=count, args=[10, 20])
t2 = threading.Thread(target=count, args=[30, 40])
# This starts the two threads and wait for bot of them to finish
#t1.start()
#t2.start()
#
#t1.join()
#t2.join()
#
# This starts one thread and wait for it to finish before starting the other
t1.start()
t1.join() # We wait for t1 to finish
t2.start() # Then we start the second thread (t2)
t2.join()
注意:您不能启动同一个线程 2 次,因此如果您想同时使用 2 个线程 运行 测试代码,请确保 comment/delete 我的部分。
编辑:我所说的程序是指主线程