繁体   English   中英

如何在python中同时运行两个同步进程

[英]How to run two synchronous process at same time in python

让两个进程function1、function2同时运行。 function1// 不断追加列表 function2// 从function1 中获取列表并从列表中获取所有数据并复制到另一个列表,刷新原始列表并处理复制的列表。

sample code:


list_p =[]
def function1(data):
     list_p.append(data)

def function2(list_p):
      list_q = list_p.copy()
      list_p.flush()
      x= process(list_q)
      return x

while True:
    //coming data continously
    function1(coming data)

那么,如何同时使用 function1 和 function2 以便我可以从 function1 获取数据并刷新它(刷新后从 0 开始在 function1 中附加索引)此外,同时列表可以附加到 function1 中。

同时,function1 可以追加列表,函数2 可以处理新列表,在完成function2 的处理后,它再次获取在function2 处理时追加的原始列表中的所有数据。

继续..

这是使用Threading的示例。 我在生产者中使用input函数代替数据流。 (它基于https://techmonger.github.io/55/producer-consumer-python/ 。)

from threading import Thread
from queue import Queue

q = Queue()
final_results = []

def producer():
    while True:
        i = int(input('Give me some number: '))  # here you should get data from data stream
        q.put(i)


def consumer():
    while True:
        number = q.get()
        result = number**2
        final_results.append(result)
        print(final_results)
        q.task_done()

t = Thread(target=consumer)
t.daemon = True
t.start()

producer()

暂无
暂无

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

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