Python 中从线程获取返回值


这篇文章首先讨论了线程的基础知识,并提供了一个在Python中启动线程的代码示例。然后,我们将讨论一个在线程中获取函数返回值的代码。

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

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


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

考虑以下代码:

from threading import Thread

# 一个线程的函数
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 类以使用多线程功能。我们定义了一个名为 first_function() 的函数,用于显示 “Hello World”,并使用 Thread() 类实例化了两个线程对象。

我们通过将 first_function() 作为目标函数传递给 Thread() 来创建了两个 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) 的函数,它接收两个参数 name 和 id。我们使用 args 在 Thread 类中将这些参数作为元组传递。

我们创建了两个 Thread 类对象,并分别将参数 args=("Thread 1", 1)args=("Thread 2", 2) 传递给 thread_1 和 thread_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_argu 和 return_val。first_function 显示 first_argu 的值,并将返回值放在 return_val 的索引 0 处。

我们使用 Thread 类创建线程,并传递两个参数,包括一个列表 args=("Thread 1", return_val_from_1)args=("Thread 2", return_val_from_2) 分别给 thread_1 和 thread_2。return_val_from_1 和 return_val_from_2 用于获取函数的返回值。

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

让我们看一下上述代码片段的输出:

Python中的线程返回值 - 输出1

使用 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 类的子类。我们重新定义了 run 和 join 方法。

一旦我们创建并启动了一个线程,join() 方法将返回从 first_function 返回的值。

以下是上述代码的输出:

Python中的线程返回值 - 输出2

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迹忆客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值