Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python的多线程处理中,为什么要在start()之后加入()呢?_Python_Multithreading - Fatal编程技术网

在python的多线程处理中,为什么要在start()之后加入()呢?

在python的多线程处理中,为什么要在start()之后加入()呢?,python,multithreading,Python,Multithreading,正如示例代码所示: for temp in range(0, 10): thread = threading.Thread(target = current_post.post) thread.start() threads.append(thread) for current in range(10): threads[current].join() 代码只是python文件的一部分,但它代表大多数情况:我应该在多线程中执行star

正如示例代码所示:

for temp in range(0, 10):
       thread = threading.Thread(target = current_post.post)
       thread.start()
       threads.append(thread)

for current in range(10):
        threads[current].join()

代码只是python文件的一部分,但它代表大多数情况:我应该在多线程中执行
start()
之后执行
join()
。几天来我一直被它弄糊涂了。我们都知道,当我们执行
thread.start()
时,一个新线程就会启动,python会自动运行不同的线程,这就是我们所需要的。如果是这样,为什么要在
start()
之后添加
thread.join()
join()
表示等待当前线程完成。但它是否意味着一种单线程?我必须等待每个线程完成任务,这不是多线程
join()
仅表示逐个执行指定的函数。无法
start()
完美完成多线程?为什么我要添加
join()
函数让它们逐个完成?thx的任何帮助:)

您这样做是为了确保您的线程已实际完成(例如,在主线程退出后,不会变成僵尸进程)


但是,您不必在启动线程后立即执行。您可以在进程的最后执行此操作。

Join将阻止当前线程,直到调用Join的线程完成为止

从本质上讲,您的代码是开始加载线程,然后等待它们全部完成


如果您没有这样做,那么很可能进程会退出,并且您的线程都不会做任何事情。

编写该示例的一种更为通俗的方法是将
temp
替换为
(未使用的临时变量的常用用法),并直接迭代
线程
列表(
用于线程中的线程
)而不是索引到它。