python thread 多线程

时间:2023-03-09 15:17:53
python thread 多线程

thread 模块在python3中改为_thread,网上的各种帖子都说不建议新手使用thread,好吃不好吃总得尝尝看。

 import _thread

 def print_num():
for i in range(100):
print(i) _thread.start_new_thread(print_num,())
_thread.start_new_thread(print_num,())
_thread.start_new_thread(print_num,())
_thread.start_new_thread(print_num,())

你猜运行结果是什么?

啥结果也没有。。。。。。因为主线程没有做任何事情直接就结束了。主线程退出的同时子线程没来得及运行就挂了,

也就是说主线成不会等待子线程执行完才退出。

下面线程锁出场了。

_thread.allocate_lock()生成一个锁,在线程函数开始的时候锁住,结束的时候解锁,主线成通过判断锁的状态决定是否退出。

 import _thread

 def print_num(lock):        #线程函数

     for i in range(100):
print(i)
lock.release() #生成5把锁
locks = []
for i in range(5):
lock = _thread.allocate_lock()
lock.acquire()
locks.append(lock)
#启动5个线程,每人一把锁
for i in range(len(locks)):
_thread.start_new_thread(print_num,(locks[i],)) #主线程分别监视每个锁的状态,知道所有的锁都不是锁定状态,退出
for i in range(len(locks)):
while locks[i].locked():
pass