Python 多线程总结

  • 主线程启动多个子线程后,默认情况下(即setDaemon(False)),主线程执行完后即退出,不影响子线程继续执行
import time
import threading

def sub_thread(i):
    print("sub_thread begin", i)
    time.sleep(i)
    print("sub_thread end", i)

print("main_thread begin")
thread_lst = []
for i in range(1, 5): 
    t = threading.Thread(target = sub_thread, args = (i, ))
    thread_lst.append(t)
for t in thread_lst:
    t.start()
time.sleep(1)
print("main_thread end")
  • 如果设置setDaemon(True),则主线程执行完后,在退出前会杀死所有子进程
import time
import threading

def sub_thread(i):
    print("sub_thread begin", i)
    time.sleep(i)
    print("sub_thread end", i)

print("main_thread begin")
thread_lst = []
for i in range(1, 5): 
    t = threading.Thread(target = sub_thread, args = (i, ))
    t.setDaemon(True)
    thread_lst.append(t)
for t in thread_lst:
    t.start()
time.sleep(1)
print("main_thread end")
  • 如果加上join,则主进程会在对应位置阻塞等待子线程结束
import time
import threading

def sub_thread(i):
    print("sub_thread begin", i)
    time.sleep(i)
    print("sub_thread end", i)

print("main_thread begin")
thread_lst = []
for i in range(1, 5): 
    t = threading.Thread(target = sub_thread, args = (i, ))
    t.setDaemon(True)
    thread_lst.append(t)
for t in thread_lst:
    t.start()
time.sleep(1)
for t in thread_lst:
    t.join()
print("main_thread end")
  • 如果设置timeout,则对应等待语句最多等待timeout秒
import time
import threading

def sub_thread(i):
    print("sub_thread begin", i)
    time.sleep(i)
    print("sub_thread end", i)

print("main_thread begin")
thread_lst = []
for i in range(1, 5): 
    t = threading.Thread(target = sub_thread, args = (i, ))
    t.setDaemon(True)
    thread_lst.append(t)
for t in thread_lst:
    t.start()
time.sleep(1)
thread_lst[0].join(timeout = 2)
thread_lst[3].join(timeout = 2)
print("main_thread end")

参考文献:

https://www.cnblogs.com/cnkai/p/7504980.html

猜你喜欢

转载自www.cnblogs.com/jhc888007/p/11359269.html