A thorough understanding of multi-threaded Python setDaemon and join in with GIF [schematic]

During Python multi-threaded programming,  the Join ()  and  setDaemon ()  is the most common method, the following talk about the usage and the difference between the two.

1、join ()

Examples: A main thread, create a sub-thread B, and the main thread B.join called A, (),

So, the main thread A will place the call blocking , until the child thread B to complete the operation before it can then execute down.

 

2、setDaemon()

Examples: A main thread, create a sub-thread B, and the main thread B.setDaemon called A, (),

Namely: the main thread A is set as a daemon thread , this time, if the main thread A executes end, on the matter sub-thread B is completed, together with A and the main thread exits.

Note: You must set before the method is called start (), if you do not set a daemon thread, the program will be infinitely suspended.

 

3, the difference

Both basically the opposite (join the main thread and other threads get away [sub] Hengdao immediately, setDaemon control of their main thread on it, ranging from sub-thread finish up [no turning back]).

 

4, the level of understanding of the code

Coding #: UTF-8 
Import Threading 
Import Time 


DEF get_list_page (): 
    Print ( "list page crawl start \ the n-") 
    the time.sleep (3) 
    Print ( "list page grab the end of \ the n-") 


DEF get_detail_page (): 
    print ( "fetch details page to start \ the n-") 
    the time.sleep (2) 
    print ( "details page grab the end of \ the n-") 


# create two sub-thread 
Thread1 = threading.Thread (target = get_list_page) 
Thread2 = threading.Thread (target = get_detail_page) 

start_time = time.time () 

# # set the thread guard 
# thread1.setDaemon (True) 
# thread2.setDaemon (True) 

# start two threads 
thread1.start () 
thread2.start () 

# # set the thread obstructive 
# thread1.join () 
# thread2.join ()

print("Run time is {}".format(time.time() - start_time)) 

operation result:

 

Explanation:

Basically three concurrent threads, the main thread, the child thread 1, thread 2 runs at the same time the child, all of the dry,

Moreover, the main thread will wait until the end of the two sub-thread, it will end.

 

Set the thread guard (setDaemon ()) that is counter-comment lines 24-26:

Explanation:

Once you have daemon thread, the main thread will end after itself, (no matter daemon thread or not running) kill off guard thread.

 

Set thread blocks (join ()) that is counter-comment lines 32-34:

Explanation:

Once you have blocked thread, the main thread will stop at the join where the end blocked waiting for child thread to run, and then continue.

 

Guess you like

Origin www.cnblogs.com/liangmingshen/p/11781433.html
Recommended