简体   繁体   中英

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. 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). After running the functions it will then use the return result a 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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM