2013-06-26 67 views
0

我有幾個工作進程應該減少共享整數完成後。Python Threadsafe整數使用鎖減少

爲了確保Threadsafety我嘗試了鎖,但不知它不工作,在程序結束時打印出的工人仍然會輸出4

我讀http://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/

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() 
+1

請給出比「不知何故它不工作」更詳細的描述。請注意,您的代碼示例不是獨立的,因此我們無法運行它並親自查看問題所在。 – user4815162342

+0

請參閱[線程和進程之間的區別](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

+0

工人最後還是4;)它也總是打印成3後打電話工人停下來 – Dukeatcoding

回答

0

THX到mtadd,他提供鏈接http://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessing/

似乎你必須以另一種方式共享不同進程之間的變量,而不是在線程之間共享

import time 
from multiprocessing import Process, Value, Lock 

def func(val, lock): 
    for i in range(50): 
     time.sleep(0.01) 
     with lock: 
      val.value += 1 

if __name__ == '__main__': 
    v = Value('i', 0) 
    lock = Lock() 
    procs = [Process(target=func, args=(v, lock)) for i in range(10)] 

    for p in procs: p.start() 
    for p in procs: p.join() 

    print v.value