0

I have a python program as follows

import multiprocessing
import time
icout=1
def send_request(data):

    lock.acquire()
    time.sleep(0.5)
    global icout
    icout=icout+1
    print(icout)
    lock.release()

def init(l):
    global lock
    lock = l

if __name__ == '__main__':
    data_list = ['data1', 'data2', 'data3']
    lock = multiprocessing.Lock()
    pool = multiprocessing.Pool(3, initializer=init, initargs=(lock,))
    pool.map(send_request, data_list)
    pool.close()
    pool.join()

When I comment out the statement time.sleep(0.5),it will print 1,2,3. When I keep the statement time.sleep(0.5),it will print 2,2,2

my question is When I keep this statement time.sleep(0.5), why is the output of the program not 1, 2, 3 I have locked it, it seems that the lock does not work.

inaMinute
  • 553
  • 2
  • 7
  • 16
  • wouldn't it be 2,3,4 without the sleep statement since it's incrementing icout from 1 before printing it? –  Sep 09 '19 at 14:20

1 Answers1

0

So, 2,3,4 notwithstanding here's a way based on a shared memory manager:

import multiprocessing
import time


def send_request(data):
    lock.acquire()
    try:
        time.sleep(0.5)
        data['c'] = data['c'] + 1
        print(data['c'])
    finally:
        lock.release()

def init(l):
    global lock
    lock = l

if __name__ == '__main__':
    data_list = ['data1', 'data2', 'data3']
    with multiprocessing.Manager() as manager:
        d = manager.dict()
        d['c'] = 1

        lock = manager.Lock()
        pool = multiprocessing.Pool(3, initializer=init, initargs=(lock,))
        pool.map(send_request, [d,d,d])
        pool.close()
        pool.join()

The idea is that globals won't work because we're spawning processes: hence we need some shared memory. That's what the manager gives us. See this answer too.