Python multi-threading creation, correlation functions and the understanding of daemon threads

Source: Internet
Author: User

One: Multi-threaded creation

Threading libraries Create threads in two ways, functional and inherited
1) Functional Type

    • def func ():

    • print ' starting '

    • print ' Ending '

    • T=threading. Thread (name= ' func ', Target=func)

    • T.start ()

2) Inheriting type

    • Class ThreadClass (threading. Thread):

    • def __init__ (self, group = none, target = none, name = none, args = (), Kwargs = {}):

    • Threading. Thread.__init__ (self, group, target, name, args, Kwargs)

    • def run (self):

    • print ' starting '

    • print ' Ending '

    • t = ThreadClass ()

    • T.start ()

The constructor for the thread class is defined as follows:

class Threading. Thread (group=none, target=none, name=none, args= (), kwargs={})

Group: reserved for threadgroup extension use, general assignment null

Target: The name of the task function to be executed by the new thread

Name: The names of the threads can also be obtained or modified using GetName (), SetName ()

Args:tuple parameters

Kwargs:dictionary parameters

Two: Correlation function

1) Start (): Start thread;

2) Join (): The main thread is blocked, waiting for the call to the function to end. The join parameter is a number, and if nonzero is represented after this time, if the thread calling join does not end the Join function also returns;

3) is_alive (), isAlive (), determine whether the thread is finished;

4) Setdaemon (), set function as Daemon thread

  • Class ThreadClass (threading. Thread):

  • def __init__ (self, group = none, target = none, name = none, args = (), Kwargs = {}):

  • Threading. Thread.__init__ (self, group, target, name, args, Kwargs)

  • def run (self):

  • While True:

  • Dosometing () ...

  • t = ThreadClass ()

  • T.setdaemon (True)

  • T.start ()

  •                                                                                                                                                   

  • while true:                                                                                                                                   

  •     if not t.is_alive ():                                                                                                              

  •         print  T is dead                                                                                                              

  • Exit (1)

  •     time.sleep                                                                                                                            

  • T.join ()

Three: Daemon thread

The concept of a daemon thread is a bit different from the concept of a Linux environment, and maybe I don't understand it, but this concept is the same as the daemon thread in Java:

The daemon thread quits after the main thread exits, and the non-daemon thread does not. What do you mean?

For normal threads, if the thread's task does not end, the main thread will not exit, and the whole program will not exit;

For a daemon thread, even if the thread task is not finished, the thread exits if the main path quits;

(I don't know if this understanding is right, experiment)

  • #--encoding= ' Utf-8 '--

  • Import logging

  • Import threading

  • Import time

  • Logging.basicconfig (

  • Level=logging. DEBUG,

  • Format= ' (% (threadname) -10s)% (message) s ',

  • )

  • Def threadfunc ():

  • Logging.debug (' starting ')

  • File_object = open (' Thefile.txt ', ' w+ ')

  • While True:

  • File_object.write (' wahaha\r\n ')

  • File_object.flush ()

  • Time.sleep (1)

  • Logging.debug (' Existing ')

  • File_object.close ()

  • T=threading. Thread (name= ' ThreadFunc ', Target=threadfunc)

  • #t. Setdaemon (True)

  • T.start ()

  • Time.sleep (5)

1) First comment out D.setdaemon (True), that is, D is a normal thread

After execution, the main thread should have exited after 5 seconds, but it was found that the thread was still entering Wahaha, and the script ran until the kill changed the execution of the script. CTRL + C is not valid at this time, only kill.

2) Delete D.setdaemon (True) in front of #, that is, D is a daemon thread

After execution, the main thread exits after 5 seconds, the thread D outputs less than five wahah and exits as the main thread exits, and the entire script exits. CTRL + C is valid before exiting.

Python multi-threading creation, correlation functions and the understanding of daemon threads

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.