简体   繁体   中英

multiprocessing in python, can i use variables for global?

hellow, please some help.

i want to take variables when using repeating statement. Actually in my code, there are so many variables and function to handle variables.

so i have to use multiprocess for some reason, but it's doesn't work for what i want.

below is simple code,

please help me.

from multiprocessing import Process, Manager
import time

def a(final_list):
   c=0
   while True:
       c += 1
       final_list.append(c)
       time.sleep(1)
       print(final_list)

def b(final_list):
  while True:
      print(final_list[-1])
      time.sleep(1)


if __name__ == '__main__':
  manager = Manager()
  final_list = []
  final_list = manager.list()

  #print(a)
  p1 = Process(target=a, args=(final_list,))
  p2 = Process(target=b, args=(final_list,))
  p1.start()
  time.sleep(3)
  p2.start()

I think you forgot to use join() for the processes. try this:

from multiprocessing import Process, Manager
import time

def a(final_list):
   c=0
   while True:
       c += 1
       final_list.append(c)
       time.sleep(1)
       print(final_list)

def b(final_list):
  while True:
      print(final_list[-1])
      time.sleep(1)


if __name__ == '__main__':
    with Manager() as manager:
        final_list = manager.list()
        p1 = Process(target=a, args=(final_list,))
        p2 = Process(target=b, args=(final_list,))
        p1.start()
        time.sleep(3)
        p2.start()
        p1.join()
        p2.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM