在Python中从一个线程中获取一个返回值

本文将首先讨论线程的基础知识和在Python中启动一个线程的代码。之后,我们将讨论从一个线程中运行的函数中获取返回值的代码。

一个线程是一个进程中的轻量级执行单元,有自己的程序执行状态。一个进程运行多个线程以实现并发性(有时是并行性)。

进程和线程的主要区别在于,每个进程都有一个独立的不相干的地址空间,而同一进程的多个线程则共享单个进程的同一个地址空间。这意味着线程可以使用共享内存进行通信,而不需要额外的管道(普通管道或FIFO)或任何消息传递接口。

HelloWorld 在Python中使用多线程的程序

考虑一下下面的代码:

from threading import Thread
# A function for threads.
def first_function():
    print('Hello World')
print ("main program start")
thread_1 = Thread(target=first_function)
thread_2 = Thread(target=first_function)
thread_1.start()
thread_2.start()
print ("main ends")

在上面的代码中,首先,我们使用from threading import Thread 语句来导入Thread 类,以使用多线程。我们定义了一个显示Hello World 的函数first_function() ,并使用Thread() 类来实例化线程。

我们通过传递first_function() 作为运行的target 函数,创建了两个Thread() 类的实例。target 属性指定了要由Thread() 执行的函数。

一旦创建了Thread() 实例,我们就可以使用.start() 方法运行和执行这些线程。

向线程中运行的函数传递参数

考虑一下下面的代码:

from threading import Thread
def first_function(name, id):
    print('Hello World from ', name, " ID= ", id)
thread_1 = Thread(target=first_function, args=("Thread 1", 1))
thread_2 = Thread(target=first_function, args=("Thread 2", 2))
thread_1.start()
thread_2.start()

在上面的代码中,我们定义了函数first_function(name, id) ,接收两个参数:nameid 。我们在Thread 类中使用args ,将这些参数作为一个元组传递。

我们创建了两个Thread 类对象,并将参数args=("Thread 1", 1)args=("Thread 2", 2) 分别传递给thread_1thread_2 。此外,thread_1.start()thread_2.start() 被用来运行这些线程。

在Python中从运行在线程中的函数中获取返回值

从一个在线程中运行的函数中获得返回值有不同的方法。

向函数传递一个可改变的对象

我们可以通过向函数传递一个可变对象,从一个在线程中运行的函数中获得一个值;函数会将返回值放在该对象中。考虑一下下面的代码:

from threading import Thread
def first_function(first_argu, return_val):
    print (first_argu)
    return_val [0] = "Return Value from " + first_argu
return_val_from_1= [None]*1
return_val_from_2= [None]*1
thread_1 = Thread(target=first_function, args=("Thread 1", return_val_from_1))
thread_2 = Thread(target=first_function, args=("Thread 2", return_val_from_2))
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
print (return_val_from_1)
print (return_val_from_2)

上面的代码定义了一个函数first_function ,它接收两个参数:first_argureturn_valfirst_function 显示first_argu 的值,并将返回值放在0 的索引中return_val

我们使用Thread 类创建线程,并传递两个参数,包括一个列表 args=("Thread 1", return_val_from_1) args=("Thread 2", return_val_from_2) ,分别为thread_1thread_2return_val_from_1return_val_from_2 用于从函数中获取值。

thread_1.join() 和 ,用于等待主程序完成两个线程。thread_2.join()

让我们来看看上述代码片断的输出情况:

在Python中从一个线程中获取一个返回值

使用join 方法

join 方法是另一种从一个线程中运行的函数中获取返回值的方法。考虑一下下面的代码:

from threading import Thread
def first_function(first_argu):
    print (first_argu)
    return "Return Value from " + first_argu
class NewThread(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs={}):
        Thread.__init__(self, group, target, name, args, kwargs)
    def run(self):
        if self._target != None:
            self._return = self._target(*self._args, **self._kwargs)
    def join(self, *args):
        Thread.join(self, *args)
        return self._return
thread_1 = NewThread(target=first_function, args=("Thread 1", ))
thread_2 = NewThread(target=first_function, args=("Thread 2", ))
thread_1.start()
thread_2.start()
print (thread_1.join())
print (thread_2.join())

在上面的代码中,我们定义了一个自定义的类,NewThread ,是Thread 类的子类。我们重新定义了runjoin 方法。

一旦我们创建一个线程并开始,first_function 的返回值就会从join() 方法中返回。

以下代码的输出如下:

在Python中从一个线程中获取一个返回值