如何编写函数并行执行(python)?

时间:2018-04-12 02:39:00

标签: python

很抱歉,如果我不知道如何给它一个正确的标题。我不能正确解释,因为英语不是我的第一语言,但我会试一试。

所以这是我的代码结构

while True:
    get_frame()
    process_frame()
    show_frame()

它以这种方式执行: get_frame() - > process_frame() - > show_frame() - > get_frame()

因此它只在处理后显示帧并显示占用太多时间的帧。我真正想要的是get_frame()在执行process_frame()时再次执行,并且process_frame()在show_frame()执行时再次执行,依此类推

这样的事情: get_frame() - > process_frame()& get_frame() - > show_frame()& process_frame()& get_frame() - >等等

1 个答案:

答案 0 :(得分:0)

好的,既然你的问题缺少一个Minimal, Complete and Verifiable例子,我将不得不猜测你想要实现的目标。

然而,我的预感是,你正在尝试按照以下方式完成某些事情:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from threading import Thread

class GetFrame(Thread):

    def __init__(self, frame):

        self.frame = frame
        Thread.__init__(self)
        self.start()

    def run(self):

        received_frame = # Code to get frame

        ProcessFrame(received_frame)


class ProcessFrame(object):

    def __init__(self, frame):

        self.frame = frame
        Thread.__init__(self)
        self.start()

    def run(self):

        processed_frame = # Code to process frame
        ShowFrame(processed_frame)

class ShowFrame(object):

    def __init__(self, frame):

        self.frame = frame
        Thread.__init__(self)
        self.start()

    def run(self):

        # Code to show frame

for frame in frame_list:

    instance = GetFrame(frame)

请注意,如果您想要处理多个帧,那么可能是实现目标的更有效方法。我的设置基本上只显示了一个非常基本的设置,可用于同时获取,处理和显示多个帧。

如果你想要更多地控制你的线程,你可以看一下python的queue module