After running the code below, the expected output should be:
[50000000.0, 50000001.0, 50000002.0, ... 50000020.0], but now the result is weird
[50000000.0, 50000000.0, 50000000.0, 50000004.0, 50000004.0, 50000004.0, 50000008.0, 50000008.0, 50000008.0, 50000008.0, 50000008.0, 50000012.0, 50000012.0, 50000012.0, 50000016.0, 50000016.0, 50000016.0, 50000016.0, 50000016.0, 50000020.0]
Is there anything wrong with my code? Python: 3.7.4, Operation system: win 10
from multiprocessing import Pool, Lock, Array, Queue
import os, time
array = Array('f', 20)
lock = Lock()
def long_time_task(i):
print('Run task %s (%s)...' % (i, os.getpid()))
start = time.time()
total_count = 0
for k in range(5*10**7): total_count += 1
total_count += i
lock.acquire()
array[i] = total_count
lock.release()
end = time.time()
print('Task %s runs %0.2f seconds.' % (i, (end - start)))
def init(l,a):
global lock
global array
lock = l
array = a
def mainFunc():
print('Parent process %s.' % os.getpid())
p = Pool(initializer=init, initargs=(lock,array))
for i in range(20): p.apply_async(long_time_task, args=(i,))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
if __name__ == '__main__':
mainFunc()
print(array[:])