如何使用线程和队列将3个相关函数排队

时间:2018-06-30 17:51:52

标签: python multithreading python-multithreading

我需要运行3个功能。每个函数都会生成下一个函数所依赖的特定输出。因此,基本上,只要第一个完成,我就可以继续第二个,但是一旦第二个运行,我就可以再次运行第一个,以生成下一批数据-因此,我想同时运行它们同时,但是我不能在完成第一个之前运行第二个,而在完成第二个之前不能运行第三个。但是我可以在第一个和第二个运行的同时运行第三个。如何在python中使用线程实现该功能?我了解线程背后的基础知识,但是我不知道如何为此目的创建队列。

这是我需要做的一个例子:

# This is what will usually happen without threading. How can I implement the
# same thing but with threading? Keep in mind that foo() 1, 2 and 3
# take some amount of time. And foo2() may finish before foo() finished
# generating data, so I can't run foo2() until I have the data from foo()

# foo generates the data for foo2
data = foo()
# foo2 generates data for foo3
data2 = foo2(data)
# foo3 does something with data2 and the data is no longer used
foo3(data2)

1 个答案:

答案 0 :(得分:0)

浏览完您的问题的评论后,我进行了更多搜索。我了解您正在寻找的是某种管道模式。而且似乎Python确实有一些功能。链接中对qn的回答还谈到了@Peterwood关于使用队列的说法。 How to design an async pipeline pattern in python