多线程和输入输出队列

时间:2021-07-15 12:10:49

标签: python multithreading queue python-import

我将以下代码保存为 exec2.py ,它启动 3 个线程,每个线程都有自己的目标函数、提交任务的输入队列、任务结果写回的输出队列。

import logging
from threading import Thread
from queue import Queue
from Temp2 import some_class


a = some_class()

# Set up some global variables
task_queue_1 = Queue()
task_queue_2 = Queue()
task_queue_3 = Queue()

result_queue_1 = Queue()
result_queue_2 = Queue()
result_queue_3 = Queue()
    

def thread_1():
    logging.debug('Looking for the next task')
    while True:
        func, args = task_queue_1.get()
        res = func(*args)
        result_queue_1.put(res)
        task_queue_1.task_done()


def thread_2():
    logging.debug('Looking for the next task')
    while True:
        func, args = task_queue_2.get()
        res = func(*args)
        result_queue_2.put(res)
        task_queue_2.task_done()


def plc_thread_3():
    logging.debug('Looking for the next task')
    while True:
        func, args = task_queue_3.get()
        res = func(*args)
        result_queue_3.put(res)
        task_queue_3.task_done()



if __name__ == "__main__":
    worker1 = Thread(target=thread_1, args=())
    worker2 = Thread(target=thread_2, args=())
    worker3 = Thread(target=thread_3, args=())

    worker3.start()
    worker2.start()
    worker1.start()

    while True:
        task_queue_1.put((a.func1, []))
        print(result_queue_1.get())

在终端中,我运行上面的代码 python3 exec2.py,线程 1 执行我提交给 task_queue_1 的 a.func1

现在在一个单独的 python 解释器中,我运行以下代码:

from exec2 import *
task_queue_3.put((a.func2,[]))

提交给线程 3 的这个任务没有运行。当我运行tasktask_queue_3.get()时,可以看到该任务已添加到队列中。

我想要实现的是 exec2.py 将启动几个工作线程。任何其他模块都应该能够从这里导入 task_queue_X 并向它们添加任务,然后由线程 X 执行

0 个答案:

没有答案
相关问题