简体   繁体   English

并行运行两个不同的进程py 3.8

[英]running two different proceses in parallel py 3.8

I want to develop a system that reads input from two devices at the same time.我想开发一个同时从两个设备读取输入的系统。 Each process works independently at the moment but since I need to sync them, I want them both to write their output on the same file.每个进程目前独立工作,但由于我需要同步它们,我希望它们都将 output 写入同一个文件。

import multiprocessing as mp
from multiprocessing import Process
from multiprocessing import Pool
import time

# running the data aquisition from the screen
def Screen(fname):

    for x in range(1, 9):
        fname.write(str(x)+ '\n')
        fname.flush()
        time.sleep(0.5)
        print(x)

# running the data aquisition from the EEG 
def EEG(fname):

    for y in range(10, 19):
        fname.write(str(y)+ '\n')
        fname.flush()
        time.sleep(0.3)
        print(y)


# main program body #

# open the common file that the processes write to
fname = open('C:/Users/Yaron/Documents/Python Scripts/research/demofile.txt', 'w+')

pool = Pool(processes=2)

p1 = pool.map_async(Screen,fname)
p2 = pool.map_async(EEG,fname)

print ('end')

fname.close()

In multiprocessing, depending on the OS you may not be able to pass an open file handle to the process.在多处理中,根据操作系统,您可能无法将打开的文件句柄传递给进程。 Here's code that should work on any OS:以下是适用于任何操作系统的代码:

import multiprocessing as mp
import time

def Screen(fname,lock):
    with open(fname,'a') as f:
        for y in range(1,11):
            time.sleep(0.5)
            with lock:
                print(y)
                print(y,file=f,flush=True)

def EEG(fname,lock):
    with open(fname,'a') as f:
        for y in range(11, 21):
            time.sleep(0.3)
            with lock:
                print(y)
                print(y,file=f,flush=True)

if __name__ == '__main__':
    fname = 'demofile.txt'
    lock = mp.Lock()
    with open(fname,'w'): pass  # truncates existing file and closes it
    processes = [mp.Process(target=Screen,args=(fname,lock)),
                 mp.Process(target=EEG,args=(fname,lock))]
    s = time.perf_counter()
    for p in processes:
        p.start()
    for p in processes:
        p.join()
    print (f'end (time={time.perf_counter() - s}s)')

Some notes:一些注意事项:

  • Open the file in each process.在每个进程中打开文件。 Windows, for example, doesn't fork() the process and doesn't inherit the handle.例如,Windows 不会 fork() 进程,也不会继承句柄。 The handle isn't picklable to pass between processes.句柄不能在进程之间传递。
  • Open the file for append.打开 append 的文件。 Two processes would have two different file pointers.两个进程将有两个不同的文件指针。 Append makes sure it seeks to the end each time. Append 确保它每次都寻找到最后。
  • Protect the file accesses with a lock for serialization.使用序列化锁保护文件访问。 Create the lock in the main thread and pass the same Lock to each process.在主线程中创建锁并将相同的锁传递给每个进程。
  • Use if __name__ == '__main__': to run one-time code in the main thread.使用if __name__ == '__main__':在主线程中运行一次性代码。 Some OSes import the script in other processes and this protects the code from running multiple times.一些操作系统将脚本import其他进程,这样可以防止代码多次运行。
  • map_async isn't used correctly. map_async 使用不正确。 It takes an iterable of arguments to pass to the function.它需要一个可迭代的 arguments 传递给 function。 Instead, make the two processes, start them, and join them to wait for completion.相反,创建两个进程,启动它们,然后加入它们等待完成。

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

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