I am trying the set an Event to communicate between 2 threads, but the event is never set in the second thread, here is what I tried so far:
import multiprocessing
import threading
import time
class Test1(multiprocessing.Process):
def __init__(self, event):
super(Test1, self).__init__()
self.event = event
def run(self):
time.sleep(10)
self.event.set()
print('event set')
class Test2(multiprocessing.Process):
def __init__(self, event):
super(Test2, self).__init__()
self.event = event
def run(self):
while not self.event.isSet():
self.event.wait()
print('event wait ended')
if __name__ == '__main__':
event = threading.Event()
test1 = Test1(event)
test2 = Test2(event)
test1.start()
test2.start()
test1.join()
test2.join()
In multiprocessing you have to use multiprocessing.Event() , not threading.Event()
BTW: And multiprocessing.Event()
needs is_set()
instead of isSet()
import multiprocessing
import time
class Test1(multiprocessing.Process):
def __init__(self, event):
super().__init__()
self.event = event
def run(self):
time.sleep(3)
self.event.set()
print('event set')
class Test2(multiprocessing.Process):
def __init__(self, event):
super().__init__()
self.event = event
def run(self):
while not self.event.is_set(): # <--- `is_set()` instead of `isSet()`
self.event.wait()
print('event wait ended')
if __name__ == '__main__':
event = multiprocessing.Event() # <--- `multiprocessing` isntead of `threading`
test1 = Test1(event)
test2 = Test2(event)
test1.start()
test2.start()
test1.join()
test2.join()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.