# -*- coding:utf-8 -*-
import _thread
import time
loops=[4,2]
def loop(nloop,nsec,lock):
print("starting loop"+str(nloop)+" at "+time.ctime())
time.sleep(nsec)
print("loop"+str(nloop)+" done at "+time.ctime())
# 释放锁
lock.release()
def main():
print("starting main at "+time.ctime())
locks=[]
nloops=range(len(loops))
# 获取锁对象
for i in nloops:
lock=_thread.allocate_lock()
lock.acquire()
locks.append(lock)
# 开启线程
for i in nloops:
_thread.start_new_thread(loop,(i,loops[i],locks[i]))
for i in nloops:
while locks[i].locked(): #如果获取了锁对象则返回True,否则,返回False
pass
print("main done at "+time.ctime())
if __name__=="__main__":
main()
Python多线程 - 使用_thread模块实现多线程
最新推荐文章于 2022-08-08 17:33:18 发布