Multithreading in Python

本文介绍了如何在Python中使用多线程进行编程。通过实例演示了如何创建线程并运行带有参数的函数,同时展示了如何获取线程返回的结果。特别强调了使用join方法确保主线程等待子线程完成的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The package for multithreading

The package threading is for multithreaded programming in python. To get it ready to use, one should import it. As:

import threading

Get your hand dirty

import threading

def add(n):
    print('I am working.')
    result = n + 1000
    return result

thread0 = threading.Thread(target=add, args=(1,))
thread0.start()

This code could be able to run. There is a function add(n) defined. Then, a thread was created to run the function. The argument, target, tells the thread which function is going to be run. The argument, args, tells the thread what is the arguments fed the target function.
NOTE: The fed value for args of the thread must be a tuple. So, if you’re going to feed the function just one value, the comma is also needed.

How to get the value returned

import threading

class MyThread(threading.Thread):

    def __init__(self,func,args=()):
        super(MyThread,self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result  # 如果子线程不使用join方法,此处可能会报没有self.result的错误
        except Exception:
            return None

def add(n):
    print('I am working.')
    result = n + 1000
    return result
################
thrdList = []
for i in range(4):
    t = MyThread(add, args=(i,))
    thrdList.append(t)
    t.start()

reslutList = []
for t in thrdList:
    t.join()
    reslutList.append(t.get_result())

print(reslutList)

output:
这里写图片描述
t.join(): It could be interpreted as wait_until_finished(t). Whitout this sentence, the thread may just have done half of its job, the main thread read its result. In this scenario, the main thread read a wrong result.

REF:
multithreading - what is the use of join() in python threading - Stack Overflow
https://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading
python multithreading wait till all threads finished - Stack Overflow
https://stackoverflow.com/questions/11968689/python-multithreading-wait-till-all-threads-finished
python - Use of threading.Thread.join() - Stack Overflow
https://stackoverflow.com/questions/19138219/use-of-threading-thread-join

Reference:

python获取多线程的返回值 - Hu知非 - 博客园
https://www.cnblogs.com/hujq1029/p/7219163.html?utm_source=itdadao&utm_medium=referral
multithreading - what is the use of join() in python threading - Stack Overflow
https://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading
python multithreading wait till all threads finished - Stack Overflow
https://stackoverflow.com/questions/11968689/python-multithreading-wait-till-all-threads-finished
python - Use of threading.Thread.join() - Stack Overflow
https://stackoverflow.com/questions/19138219/use-of-threading-thread-join

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值