处理需要并发运行的任务的最佳方法是什么?



我一直在编写一个监视linux的python代理程序。原来一切都源于一个函数,当进入一个循环收集度量标准等。但是从那以后,我添加了一些其他的特性,这些特性需要在单独的循环中运行。

例如,我有一个主指标循环,但是我也让代理在两个端口上监听不同类型的消息(尽管现在我认为我可以将其降低到单个端口)。我使用多进程来运行这些不同的循环,但遇到了进程之间共享变量的问题。有解决方案,但它只是开始看起来混乱。我也开始质疑为什么我需要这么多进程(根据角色的不同,我可以运行多达5个进程)。无论如何,你可能会说我不是一个经验丰富的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()

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

相关内容

最新更新