python的_thread模块来实现多线程(<python核心编程例子>)

python中_thread模块是一个低级别的多线程模块,它的问题在于主线程运行完毕后,会立马把子线程给结束掉,不加处理地使用_thread模块是不合适的.这里把书中讲述的有关_thread使用的例子自己实现了一遍,做以记录.

#例子一:自己手动在主线程中设置等待时间
import
_thread from time import ctime, sleep def loop0(): print("loop0 starts at:{}".format(ctime())) sleep(4) print("loop0 ends at:{}".format(ctime())) def loop1(): print("loop1 starts at:{}".format(ctime())) sleep(2) print("loop1 ends at:{}".format(ctime())) if __name__ == "__main__": print("start_time:{}".format(ctime())) _thread.start_new_thread(loop0, ()) _thread.start_new_thread(loop1, ()) #此处设置sleep(6)是因为_thread主线程结束后,会马上杀死其他线程 sleep(6) print("end_time:{}".format(ctime()))
#例子二:通过锁可以实现所有线程全部运行后立即退出
import
_thread from time import ctime, sleep #每个loop等待的时间 wait_time_list = [4, 2] def loop(i, wait_time, lock): """ 根据传入参数创建多个loop函数 :param i: :param wait_time: :param lock: :return: """ print("loop{} starts at:{}".format(i, ctime())) sleep(wait_time) print("loop{} ends at:{}".format(i, ctime())) #释放锁 lock.release() def main(): print("start_time:", ctime()) nloops = range(len(wait_time_list)) locks = []
#创建锁,上锁 for i in nloops: lock = _thread.allocate_lock() lock.acquire() locks.append(lock) #之所以另起一个循环,是为了尽量保证所有线程能够同时启动,因为上面的循环中锁的操作也要花费一些时间 for i in nloops: _thread.start_new_thread(loop, (i, wait_time_list[i], locks[i]))#loop函数中的参数放到元组里 #等待所有的子线程释放锁后,结束主线程.(等待时间取决于执行时间最长的子线程,假如第一个子线程执行时间最长,等它执行完毕,下面的循环就不会再进入了.) for i in nloops: #注意这里locked()要带括号 while locks[i].locked(): pass print("all done! end_time:", ctime()) if __name__ == '__main__': main()

猜你喜欢

转载自www.cnblogs.com/Stephen-Qin/p/10354071.html