Python线程信号
我正在寻找一些关于使用线程模块在python中实现的帮助 我有两个线程,假设线程1和线程2 我希望线程1-->向线程2发出启动信号。 直到线程1终止才终止Python线程信号,python,multithreading,python-3.x,Python,Multithreading,Python 3.x,我正在寻找一些关于使用线程模块在python中实现的帮助 我有两个线程,假设线程1和线程2 我希望线程1-->向线程2发出启动信号。 直到线程1终止才终止 是否有一种方法可以提供从线程1到线程2的信号 有点不清楚你到底想完成什么。您可能正在寻找的是等待另一个线程的threading.Thread.join(),以及唤醒另一个线程的threading.Event 这里有一个例子Thread2有一个threading.Event对象,它会阻止该对象(通过.wait()),直到Thread1有.set
是否有一种方法可以提供从线程1到线程2的信号 有点不清楚你到底想完成什么。您可能正在寻找的是等待另一个线程的
threading.Thread.join()
,以及唤醒另一个线程的threading.Event
这里有一个例子Thread2
有一个threading.Event
对象,它会阻止该对象(通过.wait()
),直到Thread1
有.set()
事件Thread1
然后调用Thread2
上的.join()
,等待它完成
同样,由于不太清楚您想要做什么,所以这个示例非常做作
import threading
class Thread1(threading.Thread):
def __init__(self, thread2):
threading.Thread.__init__(self)
self.thread2 = thread2
def run(self):
print("Hello from thread1 - I'm now running. Let's wake up thread2")
self.thread2.event.set()
print("Now thread1 waits for thread2 to quit")
self.thread2.join()
class Thread2(threading.Thread):
def __init__(self, event):
threading.Thread.__init__(self)
self.event = event
def run(self):
print("Hello from thread 2 - I'm now running, but I'll wait for thread1")
self.event.wait()
print("Hello from thread 2 - I've just woken up")
print("Now thread2 is stopping")
thread2_event = threading.Event()
thread2 = Thread2(thread2_event)
thread2.start()
thread1 = Thread1(thread2)
thread1.start()
thread1.join()
print("Everybody done")
哪张照片
Hello from thread 2 - I'm now running, but I'll wait for thread1
Hello from thread1 - I'm now running. Let's wake up thread2
Now thread1 waits for thread2 to quit
Hello from thread 2 - I've just woken up
Now thread2 is stopping
Everybody done
有点不清楚你到底想要完成什么。您可能正在寻找的是等待另一个线程的
threading.Thread.join()
,以及唤醒另一个线程的threading.Event
这里有一个例子Thread2
有一个threading.Event
对象,它会阻止该对象(通过.wait()
),直到Thread1
有.set()
事件Thread1
然后调用Thread2
上的.join()
,等待它完成
同样,由于不太清楚您想要做什么,所以这个示例非常做作
import threading
class Thread1(threading.Thread):
def __init__(self, thread2):
threading.Thread.__init__(self)
self.thread2 = thread2
def run(self):
print("Hello from thread1 - I'm now running. Let's wake up thread2")
self.thread2.event.set()
print("Now thread1 waits for thread2 to quit")
self.thread2.join()
class Thread2(threading.Thread):
def __init__(self, event):
threading.Thread.__init__(self)
self.event = event
def run(self):
print("Hello from thread 2 - I'm now running, but I'll wait for thread1")
self.event.wait()
print("Hello from thread 2 - I've just woken up")
print("Now thread2 is stopping")
thread2_event = threading.Event()
thread2 = Thread2(thread2_event)
thread2.start()
thread1 = Thread1(thread2)
thread1.start()
thread1.join()
print("Everybody done")
哪张照片
Hello from thread 2 - I'm now running, but I'll wait for thread1
Hello from thread1 - I'm now running. Let's wake up thread2
Now thread1 waits for thread2 to quit
Hello from thread 2 - I've just woken up
Now thread2 is stopping
Everybody done