I have a python program as follows
def send_request(data):
global lock
lock.acquire()
print(data)
lock.release()
if __name__ == '__main__':
data_list = ['data1', 'data2', 'data3']
lock = multiprocessing.Lock()
pool = multiprocessing.Pool(3)
pool.map(send_request, data_list)
pool.close()
pool.join()
Why did this error occur? NameError: name 'lock' is not defined.
updated
In the answer below, @Jean-François Fabre said that the reason is because “When running your subprocesses, python is "forking" and doesn't see the lock
declaration, because it doesn't execute the __main__
part in subprocesses.”
But in the following example, the subprocess should not see the lock
definition too, but why is the program working fine?
import multiprocessing
def send_request(data):
lock.acquire()
print(data,' ',os.getpid())
lock.release()
def init(l):
global lock
lock = l
if __name__ == '__main__':
data_list = ['data1', 'data2', 'data3']
lock = multiprocessing.Lock()
pool = multiprocessing.Pool(8, initializer=init, initargs=(lock,))
pool.map(send_request, data_list)
pool.close()
pool.join()