以前在C++中用过多线程pthread,现在尝试一下Python中的多线程(multi thread)
Python提供了多个内建模块用于支持多线程,可谓丰富。它们有:
- _thread
- threading.Thread
写了系列文章,本篇先介绍_thread。注意python2中这个模块称为thread,在python3中改名为 _thread.
_thread.start_new_thread 的定义如下,可以承载一个函数,并传递其元组和字典格式的参数。
1. 不使用进程锁的情况
需要注意的是,当使用strart_new_thread() 启动线程运行特定函数,必须注意有措施保障它在主程序完结前运行完成,否则主程序退出时,线程函数还没来得及执行。从表象上看,就像不工作一样。例如下面例子,
import random
import _thread as thread
from time import sleep
def fun(a, b):
print(f'Thread {a}--- {b}')
r = random.randint(1, 7)
sleep(r)
print(f"{a} exit with random {r}s.")
for i i