Python: Update Local Variable in a Parallel Process from Parent Program

后端 未结 3 2083
攒了一身酷
攒了一身酷 2021-01-26 07:14

I am relatively new to programming, and what I am asking might be a task that is not possible. What I want to do is start a parallel process, which will continuously run until

3条回答
  •  囚心锁ツ
    2021-01-26 08:04

    You can use a queue to pass data between the processes:

    from multiprocessing import Process, Queue
    from loop import loop
    
    i = 1
    q = Queue()
    q.put(i)
    p = Process(target=loop, args=(q, ))
    p.start()
    

    Whenever you want to transmit a new value of i to the other process, just put it in the queue.

    Change your loop.py module accordingly:

    def loop(q):
      while True:
        i = q.get()
        print i
    

    In your main code, you can put new values for the process:

    while True:
      i+=1
      q.put(i)
      time.sleep(1)
    

提交回复
热议问题