multiprocessing.Semaphore和multiprocessing.BoundedSemaphore有什么区别?

时间:2017-08-02 11:13:04

标签: python python-2.7 concurrency multiprocessing semaphore

multiprocessing.BoundedSemaphore(3)multiprocessing.Sempahore(3)的区别如何?

我希望multiprocessing.BoundedSemaphore(3)绝不允许其内部计数器值超过3。

由此我得出结论,即使我获取此信号量的进程最终错误地释放信号量超过一次(比如获取它一次但释放它五次),它将不允许超过3个进程获取任何时候的信号量。然而,我的这个结论似乎是不正确的。

这是我在名为multi.py的文件中的Python示例代码。

#!/usr/bin/env python
import multiprocessing
import time

def f(i, sem):
    print 'f(%d) acquiring ...' % i
    sem.acquire()
    print 'f(%d) acquired' % i

    time.sleep(i + 1)

    print 'f(%d) releasing ...' % i
    sem.release()
    sem.release() # Extra release on purpose
    sem.release() # Extra release on purpose
    sem.release() # Extra release on purpose
    sem.release() # Extra release on purpose
    print 'f(%d) released' % i

processes = []

sem = multiprocessing.BoundedSemaphore(3)
for i in range(10):
    p = multiprocessing.Process(target=f, args=(i, sem))
    p.start()
    processes.append(p)

for p in processes:
    p.join()

print 'Done'

这是我的macOS Sierra 10.12.5上使用Python 2.7.13的输出。我手动插入下面输出之间的空行,以指示输出之间的暂停。

$ ./multi.py                                                                                                                                                                            [56/1853]
f(0) acquiring ...
f(0) acquired
f(1) acquiring ...
f(1) acquired
f(2) acquiring ...
f(2) acquired
f(3) acquiring ...
f(4) acquiring ...
f(5) acquiring ...
f(6) acquiring ...
f(7) acquiring ...
f(8) acquiring ...
f(9) acquiring ...

f(0) releasing ...
f(0) released
f(3) acquired
f(5) acquired
f(4) acquired
f(6) acquired
f(7) acquired

f(1) releasing ...
f(1) released
f(9) acquired
f(8) acquired

f(2) releasing ...
f(2) released

f(3) releasing ...
f(3) released

f(4) releasing ...
f(4) released

f(5) releasing ...
f(5) released

f(6) releasing ...
f(6) released

f(7) releasing ...
f(7) released

f(8) releasing ...
f(8) released

f(9) releasing ...
f(9) released
Done

以上输出显示f(0)f(1)f(2)获取有界信号量,其余进程在尝试获取时阻止指示有界信号量的内部计数器是现在已降至0。

然后f(0)释放有界信号量5次。在此之后,我期待有界信号量的内部计数器为3(因为它是有界的),所以现在还有3个进程应该能够获得有界信号量。但是从输出看起来,有界信号量的内部计数器已经增加到5,因为5个进程获得了有界信号量。获取有界信号量的5个过程是f(3)f(5)f(4)f(7)f(7)

如果multiprocessing.BoundedSemaphore对象的内部计数器可能超过初始值,那么它与multiprocessing.Semaphore有什么不同?

1 个答案:

答案 0 :(得分:1)

关于var result = await _baseUrl .AppendPathSegment(string.Format("/Get/{0}", id)) .GetJsonAsync(); 的Python 2.7文档:

  

注意在Mac OS X上,这与Semaphore无法区分,因为   sem_getvalue()未在该平台上实现。

https://docs.python.org/2/library/multiprocessing.html#synchronization-primitives