multiprocessing.BoundedSemaphore与multiprocessing.Manager().BoundedSemaphore有何不同?

时间:2017-08-05 10:17:22

标签: python python-2.7 semaphore python-multiprocessing

我想了解multiprocessing.BoundedSemaphoremultiprocessing.Manager().BoundedSemaphore之间的区别。

以下是使用multiproessing.BoundedSemaphore

的程序
#!/usr/bin/env python
import multiprocessing
import time

def f(i, sem):
    print 'worker %d is working ...' % i
    time.sleep(5)
    sem.release()
    print 'worker %d is done' % i

def master():

    plist = []
    sem = multiprocessing.BoundedSemaphore(3)

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

    print 'waiting for processes to join ...'
    for p in plist:
        p.join()

    print 'master is done'

master()
print 'script is done'

这是输出。

$ python sem1.py 
worker 0 is working ...
worker 1 is working ...
worker 2 is working ...
worker 0 is done
worker 1 is done
worker 2 is done
worker 3 is working ...
worker 4 is working ...
worker 5 is working ...
worker 3 is done
worker 4 is done
worker 5 is done
worker 6 is working ...
worker 7 is working ...
worker 8 is working ...
worker 6 is done
worker 7 is done
worker 8 is done
waiting for processes to join ...
worker 9 is working ...
worker 9 is done
master is done
script is done

现在我只改变信号量创建代码:

    sem = multiprocessing.BoundedSemaphore(3)

    sem = multiprocessing.Manager().BoundedSemaphore(3)

我再次运行新程序。它产生与以前相同的输出,具有与以前相同的行为。以下是完成此更改的完整程序。

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

def f(i, sem):
    print 'worker %d is working ...' % i
    time.sleep(5)
    sem.release()
    print 'worker %d is done' % i

def master():

    plist = []
    sem = multiprocessing.Manager().BoundedSemaphore(3)

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

    print 'waiting for processes to join ...'
    for p in plist:
        p.join()

    print 'master is done'

master()
print 'script is done'

我的问题:

  1. multiprocessing.BoundedSemaphoremultiprocessing.Manager().BoundedSemaphore的区别如何?
  2. 何时想要使用multiprocessing.Manager().BoundedSemaphore,而使用multiprocessing.BoundedSemaphore会产生不同的结果?

0 个答案:

没有答案