Python Learning Notes-thread threading (ii) overriding the Run () method and Daemon daemon ()

Source: Internet
Author: User

Tag: Refer to its error ETH SDA-time IMP Pre

1 run () method 1.1 single Thread

In threading. The Thread () class has the run () method.

 fromTimeImportCtime,sleepImportThreading#defining the functionality of your own classclassMyThread (Threading. Thread):def __init__(Self,func,args,name =""): Threading. Thread.__init__(self) self.func=func Self.args=args Self.name=name#Call Start Auto-execute function    defRun (self): Self.func (*Self.args)defplayer (song_file,time): forIinchRange (2):        Print("start player%s.%s"%(Song_file,ctime ())) sleep (time) threads=[]t= MyThread (Player, ('You and me. mp3', 4),'Ipod') threads.append (t) T.start () T.join ()

Run

 and me. mp3. Sat APR  7 19:16:10 2018 and me mp3. Sat APR  7 19:16:10 2018

Description

(1) the Start () method calls the run () method, and the run () method calls the function

(2) the Start () method is that each thread object must be called at most once, and when more than 1 calls are made, an error is thrown; In a separate line program, it will call the run () method

(3) The run () method can be redefined in subclasses. The standard run () method invokes a callback object as a parameter to the constructor of the target object.

2.2 + Threads
#Multiple Threads fromTimeImportCtime,sleepImportThreading#defining the functionality of your own classclassMyThread (Threading. Thread):def __init__(Self,func,args,name =""): Threading. Thread.__init__(self) self.func=func Self.args=args Self.name=name#Call Start Auto-execute function    defRun (self): Self.func (*Self.args)defplayer (song_file,time): forIinchRange (2):        Print("start player%s.%s"%(Song_file,ctime ())) sleep (time) threads=[]d= {'Body.mp3': 3,"Avater.mp4"75A"You and Me.mp3": 6} forSong_file,timeinchD.items (): t= MyThread (Player, (song_file,time),'Ipod') threads.append (t) t.start () forIinchThreads:t.join ()

Run

 and Me.mp3. Sat APR  7 21:42:12 2018 and Me.mp3. Sat APR  7 21:42:12 2018start player Body.mp3. Sat APR  7 21:42:12 2018start player Body.mp3. Sat APR  7 21:42:12 2018start player Avater.mp4. Sat APR  7 21:42:12 2018start player Avater.mp4. Sat APR  7 21:42:12 2018

Note: Super () is often used in the run () statement rewriting process, specifically referencing the Python built-in function-super

2 Daemon ()

A Boolean value indicating whether this thread is a daemon thread.

A Boolean value that indicates whether the thread is a daemon thread.

The setting of this function T.daemon = True must be set before T.start () , otherwise a runtimeerror error will be thrown.

Its initial value inherits from the default value when the thread is created, and the main thread is not the daemon by default, so the default daemon for all threads created based on the main course are false.

When there are no non-daemon threads to survive, the entire Python program exits.

In short: The Daemon property in the thread, the default is False, and if set to true, all threads stop when the main thread ends.

Isdaemon (self): Gets the thread Daemon property State,

Setdaemon (self, daemonic): Set thread daemon/non-daemon thread;

When a thread is set to a daemon thread T.daemon = True or T.setdaemon (true) (before T.start () ), it means that the thread is unimportant and when the main thread exits, Do not wait for the child thread to finish to exit directly.

If you want to wait for the child thread to finish before exiting, select the default false. Or, call T.daemon = False or T.setdaemon (false) to set the thread's daemon flag. Python will not end until all non-daemon threads are exited (even if there is a daemon thread).

Example 1

Daemon = False

ImportThreading fromTimeImportSleep,ctimedefFun ():Print('Set Daemon Test') Sleep (3)    Print('thread over') T= Threading. Thread (target=Fun )#daemon default is False, so it can not be written, listed here only for comparison instructions#equivalent to T.setdaemon (False)T.daemon =Falset.start () t.join (1)Print(' all over', CTime ())

Run

set daemon testall over Sun Apr   8 21:13:33 2018thread over

Note: The results of the operation contain Threan over

Example 2

ImportThreading fromTimeImportSleep,ctimedefFun ():Print('Set Daemon Test') Sleep (3)    Print('Threan over') T= Threading. Thread (target=Fun )#equivalent to T.setdaemon (True)T.daemon =Truet.start () t.join (1)Print(' all over', CTime ())

Run

set daemon testall over Sun Apr   8 21:16:08 2018

Note: There is no thread over statement here, because when the main process finishes running, and daemon = True, exit directly.

Reference:

Python Daemon Thread

Python Concurrency and threading

Python--threading Multithreading Summary

Python Learning Notes-thread threading (ii) overriding the Run () method and Daemon daemon ()

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.