多任务并行处理多数需要用到多线程,第一次用python写一个任务,需要同时监控两个状态,就使用了下多线程,但测试时候ctrl+c居然退不出,我以为是bug,结果看了下确实是这样的。如果一个python程序用了多线程,当子线程没有结束时,用ctrl+c是关闭不了主线程的,这时候就只能用kill命令杀掉,这样会很麻烦。
像我这样新上手的肯定需要多测试,怎么能忍每次去kill
所以找了别人尝试的方法
#encoding=utf-8
import threading
from time import sleep
def func():
sleep(100)
p=threading.Thread(target=func)
p.setDaemon(True)
p.start()
while 1:
if not p.isAlive():
break
sleep(1)
print 'done'
多线程时候:
threads = []
t1 = threading.Thread(target=auto_compile,args=('./my_path',))
threads.append(t1)
t2 = threading.Thread(target=wait_analyze,args=('/home/mypath/',))
threads.append(t2)
def threads_join(threads):
'''
令主线程阻塞,等待子线程执行完才继续,使用这个方法比使用join的好处是,可以ctrl+c kill掉进程
'''
for t in threads:
while 1:
if t.isAlive():
sleep(10)
else:
break
if __name__ == "__main__":
for t in threads:
t.setDaemon(True)
t.start()
threads_join(threads)
测试时候还总是遇到解析错误,空格和tab键搞的,神烦,设置vim显示空格和tab,仔细排查,不对的就多打个空格,还不对就删除点空格。。。晕