简体   繁体   English

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

[英]How to code functions to execute in parallel (python)?

Sorry if I don't know how to give this a proper title. 对不起,如果我不知道如何给它命名。 I just cant explain properly since english is not my first language but i'll give it a try. 我无法正确解释,因为英语不是我的母语,但我会尝试一下。

So this is my code structure 这就是我的代码结构

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

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

so it only get frames after processing and showing the frame which takes too much time. 因此只有在处理并显示帧之后才获得帧,这花费了太多时间。 What I really want is for the get_frame() to execute again when process_frame() executes, and for the process_frame() to execute again when show_frame() executes, and so on 我真正想要的是让get_frame()在process_frame()执行时再次执行,以及process_frame()在show_frame()执行时再次执行,依此类推

Something like this: get_frame() --> process_frame()&get_frame() --> show_frame()&process_frame()&get_frame() --> and so on 像这样:get_frame()-> process_frame()&get_frame()-> show_frame()&process_frame()&get_frame()->依此类推

Ok, since your question lacks a Minimal, Complete and Verifiable example I am going to have to guess on what it is exactly that you want to achieve. 好的,由于您的问题缺少最小,完整和可验证的示例,因此我将不得不猜测您想要实现的目标。

However, my hunch is that you are trying to accomplish something along the lines of: 但是,我的直觉是您正在尝试实现以下目标:

#!/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)

Please note though that if you have many frames you want to process their might be far more efficient ways to achieve what you are after. 但是请注意,如果您要处理许多帧,可能是实现目标的更有效的方法。 My setup basically just shows a very basic setup that could be used to get, process and show many frames simultaneously. 我的设置基本上只显示了一个非常基本的设置,可用于同时获取,处理和显示许多帧。

If you want more control over your threads you could take a look at python's queue module . 如果您想对线程进行更多控制,可以看看python的queue模块

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

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