在用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)