[英]python multiprocessing does not run at same time
I am trying to make a python program that runs multiple processes each in an infinite loop at the same time, but only one process will execute at a time, the first one in code, then the rest of the program will not run. 我正在尝试制作一个python程序,该程序在一个无限循环中同时运行多个进程,但是一次只能执行一个进程,第一个在代码中执行,然后其余程序将无法运行。 What do i need to do to make both procceses and the main one execute at the same time?
我需要做什么才能使两个过程和主要过程同时执行?
from multiprocessing import *
import time
def test1(q):
while True:
q.put("Banana")
time.sleep(2)
def test2(q):
while True:
q.put("internet")
time.sleep(3)
if __name__ == "__main__":
q = Queue()
t1 = Process(target=test1(q))
t2 = Process(target=test2(q))
t1.start()
t2.start()
q.put("rice")
while True:
print(q.get())
The reason for your problem is with the lines: 您的问题的原因在于以下几行:
t1 = Process(target=test1(q))
t2 = Process(target=test2(q))
There you will actually call test1
and test2
, respectively (even though you will never reach the test2
call). 在那里,您实际上将分别调用
test1
和test2
(即使您永远不会到达test2
调用)。 After running the functions it will then use the return result a target
. 运行函数后,它将使用返回结果作为
target
。 What you want is: 您想要的是:
t1 = Process(target=test1, args=(q,))
t2 = Process(target=test2, args=(q,))
Thus, you do not want to actually run the test1
and test2
functions, but use their references (addresses) as target
and then you have to provide their input arguments in a separate parameter args
. 因此,您实际上不想运行
test1
和test2
函数,而是将它们的引用(地址)用作target
,然后必须在单独的参数args
提供其输入参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.