繁体   English   中英

在python中同时运行两个进程

[英]run two process simultaneously in python

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 秒后再次运行。

您需要使用 Event 来同步进程。 使用多处理,两个进程都将在一个单独的 python 实例中启动,所以它应该给你很好的时机。 看看下面的代码:

from multiprocessing import Process, Event
import os
import time


def task(event, rerun=None):
    proc_id = os.getpid()
    event.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

至于其他事情,只需使用此代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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