0

I have several workers process which should decrease a shared integer when the are finished.

To ensure Threadsafety i tried a lock but somehow it is not working, printing out workers at the end of the program will still output 4

I read 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()
Dukeatcoding
  • 1,363
  • 2
  • 20
  • 34
  • 1
    Please give a more detailed description than "somehow it is not working". Note that your code sample is not standalone, so we cannot run it and see for ourselves what the problem is. – user4815162342 Jun 26 '13 at 13:37
  • See [difference between thread and process](http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread), as well as [shared counter with python multiprocessing](http://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessing/) – mtadd Jun 26 '13 at 13:49
  • workers is at the end still 4 ;) also it is always printed as 3 after calling worker stopped – Dukeatcoding Jun 26 '13 at 13:58

1 Answers1

0

Thx to mtadd, he provided the link to http://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessing/

It seem that you have to share variables between different Process in another way than sharing between Threads

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
Dukeatcoding
  • 1,363
  • 2
  • 20
  • 34