Python 调用第二组多线程函数
我有四个函数,其中两个函数被调用以返回命令,另外两个函数接受命令并执行另一个函数。我需要函数1和2以及3和4同时运行(即,1和2同时运行,然后3和4同时运行)。我目前正在使用线程和队列模块,以便在多线程上运行前两个函数 我的代码如下所示:Python 调用第二组多线程函数,python,python-3.x,multithreading,queue,python-multithreading,Python,Python 3.x,Multithreading,Queue,Python Multithreading,我有四个函数,其中两个函数被调用以返回命令,另外两个函数接受命令并执行另一个函数。我需要函数1和2以及3和4同时运行(即,1和2同时运行,然后3和4同时运行)。我目前正在使用线程和队列模块,以便在多线程上运行前两个函数 我的代码如下所示: import queue as q import threading def function_1(queue,var): *do something* queue.put(value_1) def function_2(queue,var)
import queue as q
import threading
def function_1(queue,var):
*do something*
queue.put(value_1)
def function_2(queue,var):
*do something*
queue.put(value_2)
def function_3(value):
*do something w/ value*
def function_4(value):
*do something w/ value*
queue_1 = q.Queue()
thread_1 = threading.Thread(target=function_1, args = (queue_1, int)
queue_2 = q.Queue()
thread_2 = threading.Thread(target=function_2, args = (queue_2, int)
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
value_1 = queue_1.get()
value_2 = queue_2.get()
现在我需要将value_1
和value_2
分别传递给function_3
和function_4
(也需要这些函数尽可能同时运行),但我不需要从这些函数返回任何内容。我能打个电话吗
thread_3 = threading.Thread(target=function_3,args=(value_1)
thread_4 = threading.Thread(target=function_4,args=(value_2)
thread_3.start()
thread_4.start()
thread_3.join()
thread_4.join()
这似乎是一个直截了当的问题,但我想我对电脑里到底发生了什么感到困惑。在为
函数\u 3
和函数\u 4
调用新线程之前,线程1
和线程2
一旦完成,我是否需要知道发生了什么事情?没有什么需要知道的。你为什么这么问?有什么不起作用吗?@marineau没有,但我读过很多实例,其中用户一直在用python编写多进程函数,但这些函数实际上并没有并发运行。我只是想确保这是正确的,并且以我的方式(1/2后的3/4)调用新线程是否是正确的方法。听起来你可能会混淆多处理和多线程。后者的问题是,在Python中,线程并不是真正并发运行的,除非其中一个线程由于全局解释器锁(GIL)而等待I/O完成,而全局解释器锁正是为了阻止它而设计的。在多处理中,每个进程都有自己的解释器副本,但运行在一个单独的内存空间中,这使得它们之间的数据共享更加困难,需要克服很多开销。啊,我明白了。谢谢你的澄清。所以在我上面的例子中,我不是真的同时运行我的函数吗?除非线程正在执行I/O(或者调用用另一种语言编写的扩展,比如C,我刚刚记得的另一种情况)。对于主要进行某种计算的任务,多处理将允许实际的并发,但是这样做的开销可能会抵消由于能够这样做而获得的任何速度增益。