【Python】多线程中阻塞(join)使用误区详解

join( ) 阻塞主线程
join() 作用为阻塞主线程,即在子线程未返回的时候,主线程等待其返回然后再继续执行
join不能与start在循环里连用
以下为错误代码,代码创建了5个线程,然后用一个循环激活线程,激活之后令其阻塞主线程

threads = [Thread() for i in range(5)]
for thread in threads:
thread.start()
thread.join()
1
2
3
4
执行过程:
1. 第一次循环中,主线程通过start函数激活线程1,线程1进行计算
2. 由于start函数不阻塞主线程,在线程1进行运算的同时,主线程向下执行join函数
3. 执行join之后,主线程被线程1阻塞,在线程1返回结果之前,主线程无法执行下一轮循环
4. 线程1计算完成之后,解除对主线程的阻塞
5. 主线程进入下一轮循环,激活线程2并被其阻塞
如此往复,可以看出,本来应该并发的五个线程,在这里变成了顺序队列,效率和单线程无异

join的正确用法:使用两个循环分别处理start和join函数,即可实现并发

threads = [Thread() for i in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
---------------------
作者:brucewong0516
来源:CSDN
原文:https://blog.csdn.net/brucewong0516/article/details/81050792
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-05-07 10:56  学&无止境  阅读(2637)  评论(0编辑  收藏  举报