Python锁定共享资源(多处理)

2024-09-26 22:07:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想发送一个触发器来启动第二个进程。就像只有经过一段时间后,才能启动第二个进程。类似于锁定共享资源。我该怎么做?在

这是我的示例代码:

def worker():
    for i in range(1,10):
        if i == 5:
            # send a trigger to start the next event. 
            # Its like 'locking' a shared resource.

def main():
    for i in range(1,100):
        d = multiprocessing.Process(target = worker, args = ())
        d.daemon = True
        d.start()

已编辑(预期输出)

^{pr2}$

电流输出

Process1 loop1
Process1 loop2
Process1 loop3
Process1 loop4
1 2014-08-27 11:45:51.687848
Process1 loop5
Process1 loop6
Process1 loop7
Process1 loop8
Process1 loop9
Process2 loop1
Process2 loop2
Process2 loop3
Process2 loop4
2 2014-08-27 11:45:51.690052
Process2 loop5
Process2 loop6
Process2 loop7
Process2 loop8
Process2 loop9

Tags: infor进程defrangestartworkerprocess2
1条回答
网友
1楼 · 发布于 2024-09-26 22:07:26

我通常更喜欢通过Queue来控制进程。它为您提供了更大的灵活性,因为进程可以根据队列中的命令执行不同的操作。在

import datetime
import multiprocessing
from multiprocessing import Queue

def worker(work_queue):
    if work_queue.get() == "Start":
            for i in range(1,10):
                if i == 5:
                    # do something
                    print datetime.datetime.now() 

def main():
    worker_queues = {}
    for i in xrange(1, 6):
        q = Queue()
        worker_queues[i] = q # one queue per process here
        d = multiprocessing.Process(target = worker, args = (q,))
        d.daemon = True
        d.start()
    for wq in worker_queues.values():
        wq.put("Start")

if __name__ == "__main__":
    main()

编辑:对于您编辑的问题,您可以通过向上述解决方案中添加done queue来强制执行顺序

^{pr2}$

您可以将此解决方案理解为进程之间的一种消息传递机制。在

相关问题 更多 >

    热门问题