Python信号量卡住

2024-04-24 11:42:55 发布

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

我试图在我的程序中同时做一些事情,并限制同时打开的进程数(10)。在

from multiprocessing import Process
from threading import BoundedSemaphore

semaphore = BoundedSemaphore(10)
for x in xrange(100000):
  semaphore.acquire(blocking=True)
  print 'new'
  p = Process(target=f, args=(x,))
  p.start()

def f(x):
  ...  # do some work
  semaphore.release()
  print 'done'

前10个进程被启动并正确结束(我在控制台上看到10个“new”和“done”),然后什么都没有。我没有看到另一个“new”,程序只是挂在那里(Ctrl-C也不起作用)。怎么了?在


Tags: infromimport程序newfor进程事情
2条回答

您的问题是跨进程边界使用threading.BoundedSemaphore

import threading
import multiprocessing
import time

semaphore = threading.BoundedSemaphore(10)


def f(x):
  semaphore.release()
  print('done')


semaphore.acquire(blocking=True)
print('new')
print(semaphore._value)
p = multiprocessing.Process(target=f, args=(100,))
p.start()
time.sleep(3)
print(semaphore._value)

创建新进程时,子进程将获得父进程内存的副本。因此,子对象正在减少它的信号量,而父对象中的信号量是不变的。(通常,进程是相互隔离的:跨进程通信需要一些额外的工作;这就是multiprocessing的作用。)

这与线程相反,线程共享内存空间,被认为是同一个进程。在

multiprocessing.BoundedSemaphore可能是您想要的。(如果将threading.BoundedSemaphore替换为它,并将semaphore._value替换为信号量.get_值()`,您将看到上面的输出更改。)

您的有界信号量没有在正在生成的各个进程之间正确共享;您可能需要切换到使用multiprocessing.BoundedSemaphore。有关更多详细信息,请参阅this question的答案。在

相关问题 更多 >