Daemon and joindaemon Daemon

Source: Internet
Author: User

Daemon and joindaemon Daemon
I. Preface

A program has at least one main thread. After the main thread is started, there is no affiliation between them. The main thread and subthread are executed in parallel and independent from each other. After the execution of the main thread is completed, it will not wait until the execution of the sub-thread ends. If there are other programs, it will run another program. If not, it will wait until the sub-thread finishes executing 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 get 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 (10) print ('My name is % s. '% self. name) if _ name _ = '_ main _': start_time = time. time () for I in range (5): t = MyThread (I) t. start () # t. join () print ('main thread finished. ') print (' ***** execute another program ******* ') p = Person ('bigberg') p. get_info () print ('**************************') print ('cost: % s' % (time. time ()-start_time ))

Result:

# The thread starts to execute task 0 is operatingtask 1 is operatingtask 2 is operatingtask 3 is operatingtask 4 is operating # The main thread is finished. # You can run another program ***** to execute another program ****** my name is bigberg. * ********************** # the time consumed here is the running time of the main thread, apparently there is no cost for calculating subthreads: 0.0019881725311279297 # The Sub-Thread is still running Thread-3 finished I sleep 2 secondsThread-5 finished I sleep 2 secondsThread-2 finished I sleep 3 secondsThread-4 finished I sleep 4 secondsThread-1 finished I sleep 5 seconds after the main Thread ends # Process finished with exit code 0 after all sub-threads are completed

  

2. join waiting for the sub-thread to complete

If the main thread is blocked by default when the join clause is added to the thread instance, the main thread will wait until the sub-thread finishes running.

#-*-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 to block main thread print ('main thread finished. ') print ('cost: % s' % (time. time ()-start_time) # Note # If join is added to each thread, the concurrency will be gone. In fact, the threads are serialized # the previous thread has finished running, will execute the next thread # The main thread has finished running

Result:

Task 0 is operatingThread-1 finished I sleep 2 secondstask 1 is operatingThread-2 finished I sleep 6 secondstask 2 is operatingThread-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 finished is finished. # The consumed time is also the sum of the running time of each thread. cost: 25.005265712738037
2.1 concurrent computing Run Time

What if I don't want to calculate the total running time, but the concurrent running time of all threads? As in the preceding example, if the maximum running time is 8 seconds, all threads can be completed within 8 seconds.

Moving t. join () to the outside of the for Loop alone won't work, because the concurrent operation will always cause congestion in 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 to block main thread print ('main thread finished. ') print ('cost: % s' % (time. time ()-start_time ))

Result:

Task 0 is operatingtask 1 is operatingtask 2 is operatingtask 3 is operatingtask 4 is operatingThread-1 finished I sleep 2 secondsThread-3 finished I sleep 2 secondsThread-5 finished I sleep 3 seconds # is actually in thread 5, that is, the blocked main thread finished in the last thread. cost: 3.001293659210205Thread-2 finished I sleep 4 secondsThread-4 finished I sleep 5 seconds

The correct method is to define an empty list and obtain the thread instance. The for loop blocks all 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, it is in line with our inference that the time consumed by the thread with the longest running time is the total concurrency time.

Task 0 is operatingtask 1 is operatingtask 2 is operatingtask 3 is 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 8 secondsmain thread finished. cost: 8.001787185668945 # The concurrency is about 8 seconds.

Conclusion: after the main thread creates a subthread, if the subthread calls the join () method, the main thread will wait for the subthread to be called until the subthread runs successfully and then runs down.

Iii. Daemon

SetDaemon () method: Create a subthread in the main thread. After the subthread calls the setDaemon method, it becomes the main thread's daemon thread. In this case, if the execution of the main thread ends, whether or not the thread is complete is not required, and the main thread exits together. This is basically the opposite of the join () method. In addition, note that the program must be set before the start () method is called. If it is not set as a daemon thread, the program will be suspended infinitely.

# -*- 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

Thread Count = main thread + sub-thread count

Result:

Task 0 is operatingtask 1 is operatingtask 2 is operatingtask 3 is operatingtask 4 is operatingmain thread finished. <_ MainThread (MainThread, started 8656)> 6 cost: 0.0009999275207519531 Process finished with exit code 0 # After the sub-thread is set as the main thread's daemon thread, once the main thread ends, the program will run and quit without waiting for the sub-thread to run.

Note: if there are other non-daemon threads in the program, the program will end only after the non-daemon threads have finished running.

Related Article

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.