在 Python 中连接线程
多线程使我们能够获得完整的 CPU 优化。
线程不需要过多的内存开销,多个线程也可以进行通信和共享信息。在 Python 中,我们使用 threading
模块来处理线程。
我们现在将讨论 join()
方法与 Python 中的线程。我们使用这个函数来阻塞调用线程,直到它上面的线程被终止。
它可以正常终止或由于某些异常和超时。如果需要,也可以在 join()
函数中提及超时值。
现在让我们用一个例子来讨论这个问题。
import threading
import time
class sample(threading.Thread):
def __init__(self, time):
super(sample, self).__init__()
self.time = time
self.start()
def run(self):
print(self.time, " starts")
for i in range(0,self.time):
time.sleep(1)
print(self.time, "has finished")
t3 = sample(3)
t2 = sample(2)
t1 = sample(1)
t3.join()
print("t3.join() has finished")
t2.join()
print ("t2.join() has finished")
t1.join()
print ("t1.join() has finished")
输出:
3 starts
2 starts
1 starts
1 has finished
2 has finished
3 has finished
t3.join() has finished
t2.join() has finished
t1.join() has finished
在上面的示例中,请注意其他两个线程在 t3
完成时结束。然而,join()
函数持有主线程,其他线程等待它终止。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。