我想了解multiprocessing.BoundedSemaphore
和multiprocessing.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'
我的问题:
multiprocessing.BoundedSemaphore
与multiprocessing.Manager().BoundedSemaphore
的区别如何?multiprocessing.Manager().BoundedSemaphore
,而使用multiprocessing.BoundedSemaphore
会产生不同的结果?