python - 使用多处理模块控制 python 中的单独进程

标签 python multiprocessing python-multithreading

我想知道能够控制由 python 中的 main 函数启动的进程的最简单方法是什么。

例如,在我的主循环中,我调用了一个函数,该函数将是一个单独的进程,其唯一目的是将数据收集到缓冲区中。然后,只要我想,我就会指示该进程停止收集数据并将其存储在文本文件中。然后,当它完成写入文件时,我希望它在再次开始相同的循环之前等待另一个信号(来自 main),即将新数据收集到缓冲区。该过程将无限期地重复,但如果我能够真正停止该过程直到我需要新数据,那将是非常棒的。 我尝试使用 multiprocessing.Event() 但由于某些原因,当我使用 event.set() 或 event.clear() 时,有时无法及时收到消息,因此数据格式被搞砸了。

例子:

def separateProcess():
    datBuffer = []
    while True:
        datBuffer.append(collectData(sample))
        if signal.recv == 'TimeToWriteToFile':
            #Write the data buffer to file.
            while True:
                if signal.recv == 'NewData':
                    #Signal to begin recording new data has been received
                    datBuffer = [] #clear the buffer for new data.
                    break
        else:
            #Continue recording Data.
            pass

def main():
    #This code will do some stuff regarding the experiment.
    p = mp.Process(target=separateProcess)
    p.start()


    #Based on a particular event I will send the signal when needed.
    if experiment == 'Success':
        sendToProc('TimeToWriteToFile') #Theoretical signal to the other process.
        sleep(10) #Wait for X amount of seconds then begin recording new data.

        sendToProc('NewData')

如果需要,我可以提供我尝试创建此类脚本失败的代码示例。但基本上我想知道一种方法来实现我所拥有的,如果该方法使用全局变量作为信号,那也会很棒。我知道我不能,因为新进程不共享全局状态...

就这些。

最佳答案

您的代码看起来不错。我建议在父进程中创建一个 Queue,然后将任何内容发送给您的工作人员,工作人员将输出数据。当父 proc 希望 worker 死亡时,发送一个 None

来源

import multiprocessing, Queue

def myproc(arg):
    return arg*2

def worker(inqueue):
    for num in iter(inqueue.get, None):
        print myproc(num)


inq = multiprocessing.Queue()
# prefill with 3 jobs
for num in range(3):
    inq.put(num)
# signal end of jobs
inq.put(None)

worker_p = multiprocessing.Process(
    target=worker, args=(inq,),
)
worker_p.start()

worker_p.join()

输出

0
2
4

关于python - 使用多处理模块控制 python 中的单独进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24026968/

相关文章:

python - 当每个脚本在 python 中都有多个线程时,从主脚本同时运行两个脚本

python - Airflow :使用 BashOperator 运行时,Python 脚本如何发出失败的任务信号

linux - 同步shell脚本执行

Python 2.7 : How to compensate for missing pool. 星图?

python - Python : Is there a way to use pool. imap 中的多处理不积累内存?

python - 最大线程限制实际上是 Python/Linux 的不相关问题吗?

python - TensorFlow 2.1 调用 cuInit : UNKNOWN ERROR (303) 失败

python - 为什么 re.findall 方法在 python 中返回错误的结果?

启动 Firefox 时出现 python webdriver 错误

python - 有没有办法提高 opencv 视频处理的速度?