首页 > 解决方案 > 处理需要同时运行的任务的最佳方法是什么?

问题描述

我一直在编写一个监控 linux 的 python 代理。最初一切都源于一个单一的功能,当它进入一个循环收集指标等时。但从那时起,我添加了一些其他功能,这些功能需要在它自己的循环中单独运行到该循环。

例如,我有一个主要的指标循环,但我也让代理在两个端口上侦听不同类型的消息(尽管现在我考虑一下,我可以将其归结为单个端口)。我使用多进程来运行这些不同的循环,但遇到了进程之间共享变量的问题。有解决方案,但它刚刚开始看起来很混乱。我也开始质疑为什么我需要这么多进程(取决于角色,我最多可以运行 5 个进程)。无论如何,你可能会告诉我不是一个经验丰富的 python 开发人员(我不是一个真正的开发人员)。

我应该在这里做什么?我应该改用线程,因为它们有共享内存空间吗?这样做的最常见/普遍接受的方式是什么?

标签: python

解决方案


最常见的方式或普遍接受的方式是使用全局队列在线程之间共享信息。一种非常简单的方法是,在为要通过它们进行通信的特定信息创建全局队列之后,在不同线程中启动主程序中的不同类。看看下面:

import queue as Queue
import threading
import time

class part_1:
    def __init__(self) -> None:
        global q_input
        self.program_switch = 4

        while self.program_switch < 5:
            print('Waiting in the while loop')
            input_value = q_input.get()
            if input_value == 1:
                self.my_function()
            #stuff here running on separate thread

    def my_function(self):
            print('Stopped by input from another function')
            self.program_switch = 6
            pass
        
class part_2:
    def __init__(self) -> None:
        global q_input
        global q_output
        #stuff here running on separate thread
        value = input('Enter value 1 to stop the loop')
        q_input.put(int(value))
        print("First function will stop first but the starter function will stop late")
        time.sleep(6)
        print("it must stop late to show it is running independently")
        pass

q_input = Queue.Queue(maxsize=1)
# Put something on it as if some part tries to get them they wouldn't crash
q_input.put(0)

# Start in seperate threads first run part_2 class and then part_1
t_2 = threading.Thread(target=part_2)
t_1 = threading.Thread(target=part_1)
t_2.start()
t_1.start()

这是一个很好的开始试验的模板。如果有人对此有更好的方法,请发布或链接。我也是初学者。:) 我希望它有所帮助。


推荐阅读