python 多线程 thread (控制主线程跑完,子线程也关闭)
import thread
from time import sleep, ctime
loops = [4,2]
def loop0():
print 'start loop 0 at:', ctime()
sleep(4)
print 'loop 0 done at:', ctime()
def loop1():
print 'start loop 1 at:', ctime()
sleep(2)
print 'loop 1 done at:', ctime()
def main():
print 'start:', ctime()
a=thread.start_new_thread(loop0, ())
thread.start_new_thread(loop1, ())
sleep(6)
print 'all end:', ctime()
if __name__ == '__main__':
main()
说明:
start_new_thread()要求一定要有前两个参数。所以,就算我们想要运行的函数不要参数,我们也 要传一个空的元组。当脚本启动,实际就是启动了一个主线程,当主线程跑完,子线程也会随之关闭(无乱是否执行完)
主线程和子线程是同时执行的
我们可以把sleep(6)的位置改成去外部txt文件 查询值,当值为1 那么主线程跑完,子线程也随之的关闭掉
后记: 子线程都执行完了,主线程才关闭 的写法
#coding=utf-8
import thread
from time import sleep,ctime
def loop(nloop,lock):
print 'start loop', nloop, 'at:', ctime()
sleep(1)
print 'loop', nloop, 'done at:', ctime()
#解锁
lock.release()
def main():
print 'starting at:', ctime()
locks =[]
#创建2个带锁的对象
for i in range(2):
# 返回一个新的锁定对象,创建一个锁的列表
lock = thread.allocate_lock()
# 一个原始的锁有两种状态,锁定与解锁,分别对应 acquire()和 release() 方法。
#锁定
lock.acquire()
#追加到 locks[]数组中 ,放到锁列表 locks中
locks.append(lock)
#执行多线程(创建2条线程并带上锁)
for i in range(2):
thread.start_new_thread(loop,(i,locks[i]))
#循环监控,这2条带锁的线程,是否解锁,都解锁了 主线程就退出,脚本执行完毕
for i in range(2):
while locks[i].locked():
pass
print 'all end:', ctime()
if __name__ == '__main__':
main()
- 多线程-join方法(主线程等待子线程执行完毕)
- Python基础——_thread多线程
- (13)多线程与并发库之java5阻塞队列(BlockingQueue)的应用----子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
- unity+Loom实现多线程(Thread)和主线程(MainThread)交互
- Python实战之多线程编程thread模块
- Python多线程(Thread)
- python threading 多线程控制和处理
- 多线程在python中的使用 thread
- 【Python】threading.Event模块控制多线程
- python 进行多线程编程,使用Semaphore控制线程数
- Python 多线程 thread
- Python 多线程,threading模块,创建子线程的两种方式示例
- python--thread多线程总结
- python多线程(2)--thread和threading模块的使用
- python之潜心研究多线程(thread模块) 建议使用threading模块
- Python模块学习 ---- thread 多线程处理
- Python中利用Threadpool.map()多线程抓数据
- python 多线程中子线程和主线程相互通信方法
- 通过python threading Thread理解多线程和单线程的运行机制
- 用CountDownLatch控制主线程等待所有多线程结束