Reputation: 110
I have 2 processing, I need that when something happened on one process, something else will happen on the other. For example:
import multiprocessing
def function_1(num):
while True:
status = False
for i in range (num):
if i == 100:
status = True
i +=1
def function_2():
while True:
if status == True:
print("status changed")
if __name__ == '__main__':
num = 101
a = multiprocessing.Process(target=function_1,args=(num,))
b = multiprocessing.Process(target=function_2)
a.start()
b.start()
a.join()
b.join()
This code obviously does not work, how can I make it work? I don't need one process to end and then get the result, I need the process to continue after that... is there a way to do that?
thank you!
Upvotes: 2
Views: 155
Reputation: 106445
Instead of a using a shared variable, for the purpose of making function_2
wait until function_1
reaches a certain state, you can create a multiprocessing.Queue
instance to pass to both functions, and take advantage of the fact that Queue.get
blocks until the queue receives something to dequeue, and make function_1
put something into the queue once it reaches the desired state:
import multiprocessing
def function_1(queue, num):
while True:
for i in range(num):
print(i)
if i == 3:
queue.put(None)
def function_2(queue):
queue.get()
print('do something')
if __name__ == '__main__':
num = 5
queue = multiprocessing.Queue()
a = multiprocessing.Process(target=function_1, args=(queue, num))
b = multiprocessing.Process(target=function_2, args=(queue,))
a.start()
b.start()
Upvotes: 2
Reputation: 1099
You forgot to add .join()
after the start()
.
Try this :
a.start()
b.start()
a.join()
b.join()
Upvotes: 1