在说守护线程之前,先回归下线程的执行 threading模块
1. 没有使用join时
import threading, time
def run(i):
print('Thread %s is start' % i)
time.sleep(2)
print('thread %s is end.......' % i)
for i in range(5):
t = threading.Thread(target=run, args=(i,))
t.start()
print('主线程,all threading done...........', threading.currentThread())
执行结果:
Thread 0 is start
Thread 1 is start
Thread 2 is start
Thread 3 is start
Thread 4 is start主线程,all threading done........... <_MainThread(MainThread, started 20736)>
thread 3 is end.......
thread 1 is end.......
thread 0 is end.......
thread 4 is end.......
thread 2 is end.......
结论:子线程没有执行完时,到主线程时,主线程就可以执行,然后直到子线程执行结束,到此程序结束。所以看到的主线程的内容在中间部分
2. 使用join时
import threading, time
def run(i):
print('Thread %s is start' % i)
time.sleep(2)
print('thread %s is end.......' % i)
thread_obj = []
for i in range(5):
t = threading.Thread(target=run, args=(i,))
t.start()
thread_obj.append(t)
for thread in thread_obj:
thread.join()
print('主线程,all threading done...........', threading.currentThread())
加join执行结果:
Thread 0 is start
Thread 1 is start
Thread 2 is start
Thread 3 is start
Thread 4 is start
thread 4 is end.......
thread 3 is end.......
thread 0 is end.......
thread 2 is end.......
thread 1 is end.......
主线程,all threading done........... <_MainThread(MainThread, started 14492)>
结论:加了join之后,其它线程需要等待该线程执行结束,上述代码中,主线程会等所有子线程执行完毕后才会执行,所以 all threading done最后才会看到.
不要这样写:否则就是串行的
import threading, time
def run(i):
print('Thread %s is start' % i)
time.sleep(2)
print('thread %s is end.......' % i)
for i in range(5):
t = threading.Thread(target=run, args=(i,))
t.start()
thread.join()
print('主线程,all threading done...........', threading.currentThread())
3. 使用守护线程 setDaemon(True)
import threading, time
def run(i):
print('Thread %s is start' % i)
time.sleep(2)
print('thread %s is end.......' % i)
for i in range(5):
t = threading.Thread(target=run, args=(i,))
t.setDaemon(True)
t.start()
thread_obj.append(t)
print('主线程,all threading done...........', threading.currentThread())
执行结果:
Thread 0 is start
Thread 1 is start
Thread 2 is start
Thread 3 is start
Thread 4 is start
主线程,all threading done........... <_MainThread(MainThread, started 11496)>
结论:守护线程就是主线程一旦执行结束,守护线程就要立刻退出,因为主线程不存在的话,就不存在守护。all threading done最后看到,即子线程只执行了一部分就退出了。
|