[英]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:一些注意事项:
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
其他进程,这样可以防止代码多次运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.