0
我有幾個工作進程應該減少共享整數完成後。Python Threadsafe整數使用鎖減少
爲了確保Threadsafety我嘗試了鎖,但不知它不工作,在程序結束時打印出的工人仍然會輸出4
workers = 4
lock = threading.Lock()
def workerStopped(id,lock):
lock.acquire()
global workers
print "Decrease workers (" + str(workers) + ")for #" + str(id)
workers = workers - 1
print "Now " + str(workers) + " Workers"
lock.release()
class Worker(Process):
def __init__(self, queue,ident,lock):
super(Worker, self).__init__()
self.queue= queue
self.idstr= str(ident)
self.lock = lock
print "Ident" + self.idstr
......
workerStopped(self.idstr,self.lock)
....
for i in range(4):
Worker(request_queue,i,lock).start()
請給出比「不知何故它不工作」更詳細的描述。請注意,您的代碼示例不是獨立的,因此我們無法運行它並親自查看問題所在。 – user4815162342
請參閱[線程和進程之間的區別](http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread),以及[與...共享計數器python multiprocessing](http://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessing/) – mtadd
工人最後還是4;)它也總是打印成3後打電話工人停下來 – Dukeatcoding