Python multi-threading threading and join, setDaemon functions

Multi-threading usage examples

import threading
import time
def subThread(threadID):
    print(f'-- thread{
      
      threadID} START!')
    time.sleep(4)
    print(f'-- thread{
      
      threadID} END!')
def main():
    threads = []
    for i in range(3):
        threads.append(threading.Thread(target=subThread, args=(i,)))
    for t in threads:
        t.setDaemon(False)
        t.start()
        time.sleep(1)
    for i, t in enumerate(threads):
        print(f'-- thread{
      
      i} JOIN.')
        t.join(.5)
    print('Main Thread END!')
    return 0

if __name__ == '__main__':
    main()
    print('Program END!')

Program execution sequence analysis

Program output

setDaemon( False )
setDaemon( True )

join() function:

  • Function: Used for thread synchronization, making the main thread wait for the child thread.
  • t.join() makes the main thread wait for the sub-thread t here until the sub-thread t finishes executing, and then the main thread continues execution.
  • t.join(time) makes the main thread wait here for up to time seconds. After the sub-thread t completes execution or time seconds later, the main thread continues execution. Note: Child thread t will not be killed after timeout.

setDaemon() function:

  • Function: Allow unimportant sub-threads to be killed, preventing the sub-threads from endless loops and preventing the main thread from exiting.
  • The setDaemon() function must be executed before t.start().
  • t.setDaemon(False) is the default value. At this time, the main thread will not exit the program immediately after executing its last line of code, but will wait for the sub-thread t to finish executing before exiting.
  • t.setDaemon(True), at this time, the main thread exits the program directly after executing the last line of code, and kills the unfinished child thread t.

After studying Python's multi-threading for a long time, I found that it is easy to make mistakes in the usage of the two functions join and setDaemon. I hereby record it. If I am wrong, please give me some advice! !

Guess you like

Origin blog.csdn.net/jasonso97/article/details/120755985