Multi-threaded Python summary

  • After the main thread to start multiple sub-thread, by default (ie setDaemon (False)), after the implementation of the main thread to exit does not affect the child thread to continue
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")
  • If setDaemon (True), the main thread executed, before exiting will kill all child processes
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")
  • If we add join, the main process will block waiting in the corresponding sub-thread end position
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")
  • If timeout, a maximum wait statement corresponds wait timeout seconds
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")

 

 

references:

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

 

Guess you like

Origin www.cnblogs.com/jhc888007/p/11359269.html