在 Python 中连接线程
Manav Narula
2022年5月17日
多线程使我们能够获得完整的 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()
函数持有主线程,其他线程等待它终止。
作者: Manav Narula
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn