在python中同时运行两个进程

时间:2018-11-13 17:44:03

标签: python multiprocessing

import multiprocessing as mp .   
from multiprocessing import Process, Queue, Manager .   
from threading import Thread .   
from subprocess import Popen, PIPE, STDOUT .  

count = 0   
def loop1():  
     while True:
         for i in range(0, 100): 

             count = count + 1 . 

             time.sleep(2)
             if count == 100:
                  count = 0


def worker(filename):  

        proc = Popen(["{0}".format(filename)], stdout=PIPE, stderr=STDOUT, shell=True)
       (proc.communicate()[0])



def loop2():

    while True:  
        for i in ["a.py", "b.py"]:  
            if count == 50:  
                # run some executable in background and do not wait for it . 
                p = Process(target=worker, args=(i)) . 
                a.sleep(2)   


if __name__ == '__main__':  

    T1 = Thread(target=loop1, args=()) 
    T2 = Thread(target=loop2, args=()) 
    T1.start() . 
    T2.start() . 
    #T1.join() . 
    #T2.join()

1)我应该如何并行启动两个方法?我需要在method2中检查method1的变量状态吗? T1.start()和T2.start()一次不一次启动。

2)loop2的任务必须在50秒后再次运行。

1 个答案:

答案 0 :(得分:0)

您需要使用事件来同步进程。通过多处理,两个进程都将在单独的python实例中启动,因此它应该为您提供很好的时机。看看下面的代码:

from multiprocessing import Process, Event
import os
import time


def task(event, rerun=None):
    proc_id = os.getpid()
    e.wait()  # Wait for an event
    print('timestamp of process id {}: {}'.format(proc_id, time.time()))
    if rerun is not None:
        time.sleep(rerun)
        print('timestamp of process id {}: {}'.format(proc_id, time.time()))


if __name__ == '__main__':
    e = Event()  # Create event that will be used for synchronization

    p1 = Process(target=task, args=(e,))
    p1.start()

    # Start second task with rerun after 2 seconds
    p2 = Process(target=task, args=(e, 2))
    p2.start()

    e.set()  # Set event so all processes can start at the same time

这将产生如下输出:

timestamp of process id 28415: 1542278592.7580822
timestamp of process id 28416: 1542278592.7585154
timestamp of process id 28416: 1542278594.7604039

对于其他事情,只需使用此代码即可