Python 线程_thread

作者:zhuge···预计阅读 9 分钟·594 阅读·0 评论
Python  线程_thread

使用线程锁,主线程可以在子线程都退出后立即退出。

import _thread
from time import sleep
from datetime import datetime

def get_date_str(dt):     return datetime.strftime(dt, '%Y-%m-%d %H-%M-%S')

def subthread(thid, sec, lock):     print(f'subthread-线程{thid},Start at {get_date_str(datetime.now())} ,sleep{sec} s')     sleep(sec)     print(f'subthread-线程{thid},End at {get_date_str(datetime.now())} ,sleep{sec} s')     lock.release()

def subthread2(thid, sec, lock):     print(f'subthread2-线程{thid},Start at {get_date_str(datetime.now())} ,sleep{sec} s')     sleep(sec)     print(f'subthread2-线程{thid},End at {get_date_str(datetime.now())} ,sleep{sec} s')     lock.release()

def main():     print('-'  10 + 'ALL START:' + get_date_str(datetime.now()) + '-'  10)     locks, loops = [], [4, 2]     for i in range(len(loops)):         lock = _thread.allocate_lock()         lock.acquire()         locks.append(lock)

    for i in range(len(loops)):         _thread.start_new_thread(subthread, (i, loops[i], locks[i]))

    #启动另一个方法     lock = _thread.allocate_lock()     lock.acquire()     locks.append(lock)     _thread.start_new_thread(subthread2, (1, 1, locks[2]))

    for i in locks:         while i.locked(): pass

    print('-'  10 + 'ALL End:' + get_date_str(datetime.now()) + '-'  10)

if name=='main':     main()


相关文章

评论

加载中...