简体   繁体   English

python中的多处理,我可以使用全局变量吗?

[英]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.我认为您忘记对流程使用join() 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在python中使用多重处理时,可以安全使用全局队列吗? - Can I safely use global Queues when using multiprocessing in python? 多处理中的全局变量 (Python) - Global variables in multiprocessing (Python) Python 如何在 class 中使用全局变量 - Python How can I use global variables in a class 如何在多处理中将模块用于“全局”变量? - How to use a module for “global” variables with multiprocessing? python中的多处理模块和修改共享全局变量 - multiprocessing module in python and modifying shared global variables 如何在生成器中使用 python 多处理? - How can I use python multiprocessing with generators? 如何在 python 中使用多处理从 append 到 class 变量? - How can I append to class variables using multiprocessing in python? 如何避免使用全局变量? (python-flask-socketio应用) - How can I avoid to use global variables? (python - flask-socketio app) 在Python中,如何在第二个函数中使用函数的return语句而不使用全局变量? - In Python, how can I use a function's return statement within a second function without using global variables? Python多重处理-共享ID的单独进程中的全局变量? - Python multiprocessing--global variables in separate processes sharing id?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM