How do multiple processes share global variables in python3?

Code

from multiprocessing import Pool, Queue
import os, time, random

def long_time_task(name, queue):
    print("Run task %s (%s)..." % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print("Task %s runs %0.2f seconds." % (name, (end - start)))
    print(queue.get())

if __name__=="__main__":
    print("Parent process %s." % os.getpid())
    p = Pool(2)
    q = Queue(10)
    for j in range(10):
        q.put(j)
    for i in range(5):
        p.apply_async(long_time_task, args=(i, q))
    print("Waiting for all subprocesses done...")
    p.close()
    p.join()
    print("All subprocesses done.")

the above code will not work and will not perform the desired effect.
what should I do if I want to share a global queue among multiple processes? After the Google has passed, it is still not clear of the knowledge points in it. Trouble seniors to solve their doubts.

Mar.17,2021

if multiple processes share a global queue, there are no more than two cases. A global queue is stored in memory, for example, a global queue is stored on a hard disk using redis, such as database mysql.
for multi-process communication, you can also consider that pipe and socket, multiprocessing.Manager.Queue are pipe communications.

from multiprocessing import Pool, Manager
import os, time, random

def long_time_task(name, queue):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))
    print(queue.get())

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(2)
    q = Manager().Queue(10)
    for j in range(10):
        q.put(j)
    for i in range(5):
        p.apply_async(long_time_task, args=(i, q))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')
Menu