简体   繁体   中英

How to write multiprocessing code correctly in Python 2

I'm trying to implement very simple multiprocessing code in python 2.7, but it looks like the code run serially and not parallel. The following code prints *****1***** while I expect it to print *****2***** immediately after *****1*****.


import os
import multiprocessing
from time import sleep


def main():
    func1_proc = multiprocessing.Process(target=func1())
    func2_proc = multiprocessing.Process(target=func2())

    func1_proc.start()
    func2_proc.start()

    pass

def func1():
    print "*****1*****"
    sleep(100)

def func2():
    print "*****2*****"
    sleep(100)

if __name__ == "__main__":
    main()

You're calling func1 and func2 before passing their returning values to Process , so func1 is going to sleep 100 seconds before returning None , for which Process will raise an error.

You should pass function objects to Process instead so that it will run them in separate processes:

func1_proc = multiprocessing.Process(target=func1)
func2_proc = multiprocessing.Process(target=func2)

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