Python3 的多线程使用:_thread,threading,multiprocessing

本文介绍了Python中三种多线程的实现方式:_thread、threading及multiprocessing,并提供了具体的使用示例。从简单的_thread模块到更强大的threading模块,再到能够利用线程池的multiprocessing,每种方式都有其适用场景。

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

在用Python的多线程,之前一直都是用到的时候去搜,现在记录一下。
多线程可以通过bash脚本实现,我感觉更方便:

trap 'echo exit && kill $(ps aux | grep '"'"'[p]ython3 mult'"'"' | awk '"'"'{print $2}'"'"')' EXIT
cat test.sh
if [ "$1" != "" ]; then
    echo "Positional parameter 1 contains something"
    for ((i=1; i<=$1; i++)); do
        python3 mult.py &
    done
else
    echo "Positional parameter 1 is empty"
    exit
fi
wait 

参考网址:Python3 多线程 | 菜鸟教程

1._thread

这是Python2遗留下来的线程,使用方法如下:

_thread.start_new_thread ( function, args )

_thread最大的问题是不能join,也就是你不知道线程什么时候完成任务。
不推荐使用

2.threading

推荐使用,方法如下:

# 创建新线程
thread1=threading.Thread(target=function)
thread2=threading.Thread(target=function)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("thread all finish")

3.multiprocessing

multiprocessing封装了threading,可以使用线程池,使用方法如下:

from multiprocessing import Pool
args=[i for i in range(1,9)]
pool = Pool(processes=8)
pool.map(function,args)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值