Join and Daemon Daemon threads

Source: Internet
Author: User

First, preface

A program has at least one main thread, and after the main thread initiates a child thread, there is no affiliation between them. The main thread and the child threads are executed in parallel and independent of each other. After the main thread executes, the default is not equal to the end of the child thread execution and then goes down, if there are other programs will run another program, if not just wait for the child thread to complete after the completion of the program.

Import Threadingimport timeimport randomclass MyThread (threading. Thread):    def __init__ (self, N):        super ("MyThread, Self"). __init__ ()        SELF.N = n    def run (self):        print (' task%s is operating '% SELF.N)        T_time = Random.randint (1, 8)        time.sleep (t_time)       # Getnname Gets the thread name        print (Self.getname (), ' finished ', ' I Sleep%d seconds '% T_time) class Person (object):    def __init__ (self, name):        self.name = name    def get_info ( Self):        # time.sleep        print (' My name is%s. '% self.name) if __name__ = = ' __main__ ':    start_time = Time.ti Me () for    I in range (5):        t = MyThread (i)        T.start ()    # t.join ()    print (' main thread finished. ')    Print (' * * * * * * * * * * ****** ')    p = person (' Bigberg ')    p.get_info ()    print (' ******************** ')    print (' Cost:%s '% (Time.time ()-start_time))

Results:

# thread starts executing task 0 is operatingtask 1 are operatingtask 2 is operatingtask 3 are operatingtask 4 is operating# main thread finishes executing main threa D finished.# can execute another program * * * * * * * * * * * * * ******my name is bigberg.*************************# the time spent here is the running time of the main thread, Obviously there is no time to calculate the cost:0.0019881725311279297# child thread is still running after the main thread ends Thread-3 finished I sleep 2 secondsThread-5 finished I sleep 2 sec OndsThread-2 finished I sleep 3 secondsThread-4 finished I sleep 4 secondsThread-1 finished I sleep 5 seconds# All sub-threads complete with the program knot Bundle process finished with exit code 0

  

Second, join waits for the child thread to complete

If the thread instance is blocked after adding the join default main thread, the main thread waits for the child thread to finish running after completion.

#-*-Coding:utf-8-*-import threadingimport timeimport randomclass MyThread (threading. Thread):    def __init__ (self, N):        super ("MyThread, Self"). __init__ ()        SELF.N = n    def run (self):        print (' task%s is operating '% SELF.N)        T_time = Random.randint (1, 8)        time.sleep (t_time)        print (Self.getname (), ' finished ', ' I sleep%d seconds '% t_time if __name__ = = ' __main__ ':    start_time = Time.time () for    I in range (5):        t = MyThread (i)        T.start ()        T.join ()    # Add join, block main thread    print (' main thread finished. ')    Print (' Cost:%s '% (Time.time ()-start_time) # Note # If you add a join to each thread, then there is no concurrency, and the thread is actually serial # the previous thread executes before executing the next thread # The main thread finally finishes running

Results:

Task 0 is operatingThread-1 finished I sleep 2 Secondstask 1 are operatingThread-2 finished I sleep 6 secondstask 2 is oper AtingThread-3 finished I sleep 4 secondstask 3 is operatingThread-4 finished I sleep 8 secondstask 4 is operatingThread-5 Finished I sleep 5 seconds# Here the main thread is already the last execution of the main thread finished.# the elapsed time is also the sum of the running time of each thread cost:25.005265712738037
2.1 Calculating the Concurrency run time

If you do not want to calculate the total elapsed time, but the concurrency of all threads? As in the example above, the maximum run time is 8 seconds, so all threads can be completed in 8 seconds.

It is not possible to move t.join () to the outside of the For loop alone, because the concurrency will always be blocked on the last thread. As follows:

#-*-Coding:utf-8-*-import threadingimport timeimport randomclass MyThread (threading. Thread):    def __init__ (self, N):        super ("MyThread, Self"). __init__ ()        SELF.N = n    def run (self):        print (' task%s is operating '% SELF.N)        T_time = Random.randint (1, 8)        time.sleep (t_time)        print (Self.getname (), ' finished ', ' I sleep%d seconds '% t_time if __name__ = = ' __main__ ':    start_time = Time.time () for    I in range (5):        t = MyThread (i)        T.start ()    T.join ()    # Add join, block main thread    print (' main thread finished. ')    Print (' Cost:%s '% (Time.time ()-start_time))

Results:

Task 0 is Operatingtask 1 are operatingtask 2 is operatingtask 3 are operatingtask 4 is operatingThread-1 finished I sleep 2 SecondsThread-3 finished I sleep 2 secondsThread-5 finished I sleep 3 seconds# is actually thread 5, that is, the last threading out of the blocked main thread finished. Cost:3.001293659210205thread-2 finished I sleep 4 secondsThread-4 finished I sleep 5 seconds

The correct way to define an empty list, get the thread instance that is so, the for loop blocks all the thread instances

#-*-Coding:utf-8-*-import threadingimport timeimport randomclass MyThread (threading. Thread):    def __init__ (self, N):        super ("MyThread, Self"). __init__ ()        SELF.N = n    def run (self):        print (' task%s is operating '% SELF.N)        T_time = Random.randint (1, 8)        time.sleep (t_time)        print (Self.getname (), ' finished ', ' I sleep%d seconds '% t_time if __name__ = = ' __main__ ':    t_list = []    start_time = Time.time () for    I in range (5):        t = MyThread (i) 
   
    t.start ()        t_list.append (t) for    T in T_list:        t.join ()    print (' main thread finished. ')    Print (' Cost:%s '% (Time.time ()-start_time))
   

As a result, in fact, as we have just concluded, the longest running thread consumes time, which is the total concurrency time

Task 0 is Operatingtask 1 are operatingtask 2 is operatingtask 3 are operatingtask 4 is operatingThread-3 finished I sleep 3 SecondsThread-5 finished I sleep 3 secondsThread-2 finished I sleep 7 SecondsThread-1 finished I sleep 7 secondsThread-4 Finished I sleep 8 secondsmain thread finished.cost:8.001787185668945# concurrency time in about 8 seconds

Summary: After the main thread creates a child thread, if the child thread calls the join () method, the main thread waits in place of the call until the child thread finishes running.

Third, the Guardian thread Setdaemon

Setdaemon () Method: Creates a child thread in the main thread that calls the Setdaemon method and becomes the daemon thread of the main thread. In this case, if the main thread executes, the thread exits regardless of whether the child thread is complete or not. Here the basic and join () methods are reversed. In addition, there is a special note that must be set before the start () method call, and if not set to the daemon thread, the program will be indefinitely suspended.

#-*-Coding:utf-8-*-import threadingimport timeimport randomclass MyThread (threading. Thread):    def __init__ (self, N):        super ("MyThread, Self"). __init__ ()        SELF.N = n    def run (self):        print (' task%s is operating '% SELF.N)        T_time = Random.randint (1, 8)        time.sleep (t_time)        print (Self.getname (), ' finished ', ' I sleep%d seconds '% t_time if __name__ = = ' __main__ ':    start_time = Time.time () for    I in range (5):        t = MyThread (i)        T.setdaemon ( True)        T.start ()    print (' main thread finished. ', Threading.current_thread (), Threading.active_count ())    print (' Cost:%s '% (Time.time ()-start_time))

Note: Threading.current_thread () View the currently running thread

Threading.active_count () View the number of active threads

Number of threads = Main thread + number of child threads

Results:

Task 0 is Operatingtask 1 are operatingtask 2 is operatingtask 3 are operatingtask 4 is Operatingmain thread finished. <_mainthread (Mainthread, started 8656) > 6cost:0.0009999275207519531process finished with exit code 0# It is obvious that when the thread is set to the daemon thread of the main threads, the program exits and no longer waits for the child thread to run once the main process is finished.

Note: If there are other non-daemon threads in the program, the program will not end until the non-daemon thread has finished running.

Join and Daemon Daemon threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.