0

我有几个工作进程应该在完成后减少一个共享整数。

为了确保线程安全,我尝试了一个锁,但不知何故它不起作用,在程序结束时打印出工作人员仍将输出 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()
4

1 回答 1

0

感谢 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
于 2013-06-26T14:39:34.907 回答