About Python Process thread coprocessor Threading module (i) Thread class __python

Source: Internet
Author: User
Tags semaphore thread class true true
threading all objects in the module:

Thread : represents the execution object lock of one thread: Lock originated from Object Rlock: Can be reentrant to lock object so that a single thread can get the acquired lock again (recursive lock)

Condition: A condition variable allows a thread to stop waiting for another thread to meet a condition. If a state change satisfies a value or a state

Event: a common condition variable. Multiple threads can wait for an event to occur, and all threads will be activated after the event occurs

semaphore: A structure that provides a similar waiting room for a thread waiting for a lock

Boundedsemaphore: similar to semaphore, except that it is not allowed to exceed the initial value

Timer: Similar to Thread, it only waits a period of time before it starts running the thread class:

Threading thread Class object is the main multithreaded running object , with thread class you can create objects in a variety of ways, here mainly introduces three kinds:

Method I. Create an instance of thread and pass it a function;
method Two. Create an instance of thread and pass it to a callable class object;
method Three. Derive a subclass from thread and create an instance of this subclass.

methods of the thread class: Start (): begin thread Execution run (): defines the function function of the thread, which is used (subclass overrides the Run method of the parent Class) Join (timeout = None) When applying the method described above three o'clock: The program hangs until the thread ends, and if timeout is given, the maximum block timeout seconds getName (): Returns the name of the thread setname (name) : Set the name of the thread isAlive (): Boolean flag that indicates whether this thread is still running Isdaemon (): returns the thread's daemon flag Setdaemon (TRUE or False): true: The thread is set as the daemon thread; False: The main thread will be suspended about the start () method source code is as follows:

About the start () method to begin the execution of the thread, in the source code is actually running the Run method

Class Thread (_verbose): ... Omit multiple places ... def __init__ (self, group=none, Target=none, Name=none, args= (), Kwargs=none, Verbose=none ):

       ...... Omit multiple places ... if Kwargs is None:kwargs = {} Self.__target = target self.__name = str (NA
        Me or _newname ()) Self.__args = args Self.__kwargs = Kwargs self.__daemonic = Self._set_daemon () ...... Omit multiple places ... def start (self): .... Omit multiple places ... try: _start_new_thread (Self.__bootstrap, ()) except Excepti
                On:with _active_limbo_lock:del _limbo[self] Raise
            Self.__started.wait () def __bootstrap (self): Try:self.__bootstrap_inner () Except:if Self.__daemonic and _sys is None:return raise de F __bootstrap_inner (self): try:
                ...... Omit many places ... Try:self.run () ..... Omit multiple places ... def run (self): Try:if self.__target:self.__target (*self.__args, **s Elf.__kwargs) Finally:del Self.__target, Self.__args, Self.__kwargs
Example One:

Method I. create an instance of thread and pass it a function

# _*_coding:utf-8_*_ Import threading from time import Sleep,ctime ' "" "the process that intruduce class of thread" "" _
Time = [2,4,6,8] # thread hang the maximum number of times _maxlink = Len (_time) # A Pool of thread max-link thread pool = []  # A pool of thread that save instantiation threads the thread pool def Loop (Index,time) that holds threads instances: "" "a function to class thread For sleep some times "print" Start loop%s at: "%index,ctime (Time[index]) print" End loop%s at: " %index,ctime () def thread_pool (*arg): "" "A function that is create and save instantiation of threading to Thread p Ool "" "Func,ln,time = arg for i in range (LN): t = Threading.
    Thread (target = Func,args = (i,time)) _thread_pool.append (t) # puts the threading instance into thread pool def thread_start (ARG):
    "" A function that is represents a thread of control. "" " For I in range (ARG): _thread_pool[i].start () def main (): "" "" A Function of main "" print "process start A T: ". Upper (), CTime () Thread_pool (loop,_maxlink,_time) thread_start (_maxlink) print" Process end at: ". Upper (), C Time () if __name__ = = ' __main__ ': Main ()
Run Result:
PROCESS START at:  Fri Apr 10:12:02 2017
start loop 0 at:  Fri Apr 10:12:02 2017
START Loop 1 at:  Fri Apr 10:12:02 2017
start loop 2 at:  Fri Apr 10:12:02 2017
start loop 3 at:process end at:   Fri A  PR 10:12:02 2017Fri Apr 10:12:02 2017 end

Loop 0 at:  Fri Apr 10:12:04 2017 end
Loop 1 at:  Fri Apr 10:12:06 2017 End
Loop 2 at:  Fri Apr 10:12:08 2017 end
Loop 3 at:  Fri APR 28 10:12:10 2017

PS: before the main thread runs out, it hangs until all child threads have run out on the daemon (about method: Setdaemon Isdaemon):

The threading module introduces the concept of a daemon thread , which means that by default the main thread waits for all child threads to run and then exits after an instance of the thread class sets true by calling the Setdaemon method before calling the Start method. Setdaemon (ture), this way the thread instance will be set to the daemon thread, that is, the primary thread will not wait for the child thread to run out of the exit, but run the direct exit, but this will cause the child thread is not running out of the case, is forced to quit , The default setting is Setdaemon (False), and all child threads of instance one are executed, which confirms that the main thread is suspended until all child threads have run out. Example Two:

Active Set Setdaemon (True), compare instance one, all child threads of instance two (running) are forced to quit when the main thread runs out, but there is no error (the thread module will complain)

# _*_coding:utf-8_*_ Import threading from time import Sleep,ctime ' "" "the process that intruduce class of thread" "" _
Time = [2,4,6,8] # thread hang the maximum number of times _maxlink = Len (_time) # A Pool of thread max-link thread pool = []  # A pool of thread that save instantiation threads the thread pool def Loop (Index,time) that holds threads instances: "" "a function to class thread For sleep some times "print" Start loop%s at: "%index,ctime (Time[index]) print" End loop%s at: " %index,ctime () def thread_pool (*arg): "" "A function that is create and save instantiation of threading to Thread p Ool "" "Func,ln,time = arg for i in range (LN): t = Threading. Thread (target = Func,args = (i,time)) T.setdaemon (True) #将子线程设置为守护线程 print T.isdaemon ( #打印线程是否为守护线程 _thread_pool.append (t) # puts the thread instance into thread pool def thread_start (ARG): "" A F Unction that represents a thread of control. "" For I in RanGE (ARG): _thread_pool[i].start () def main (): "" "A Function of main" "print" process start at: ". Upper (  ), CTime () Thread_pool (loop,_maxlink,_time) thread_start (_maxlink) print "Process end at:". Upper (), CTime () if __name__ = = ' __main__ ': Main ()
Run Result:
PROCESS START at:  Fri Apr 10:31:23 2017 True to True True
START Loop 0 at:  Fri Apr 28 10: 31:23 2017
start loop 1 at:  Fri Apr 10:31:23 2017
start loop 2 at:  Fri Apr 10:31:23 2017
PRO CESS End At:start Loop 3 at:   Fri Apr 10:31:23 2017Fri APR 28 10:31:23 2017

PS: the child thread is set as the daemon thread, the thread does not run when the main thread is not suspended, the main thread exits after execution, and the child thread is forced to quit on the Join method source code as follows:

About Join method : Thread also provides a join method that suspends the main thread until it is finished and also adds a lock to the entire thread to prevent dirty data from being generated

Class Thread (_verbose):
    ... Omit many places


    ... def __init__ (self, group=none, Target=none, Name=none,
                 args= (), Kwargs=none, Verbose=none):
        ... Omit many places

        ... Self.__block = Condition (Lock ())
    def join (self, timeout=none):
            ... Omit many places
            ... Self.__block.acquire () ...
Omit many places


... Class _condition (_verbose):
        def __init__ (self, Lock=none, verbose=none):
        _verbose.__init__ (self, Verbose)
        if Lock is None:
            lock = Rlock ()
        self.__lock = Lock
        # Export The lock's Acquire () and release () method s
        self.acquire = lock.acquire
        self.release = Lock.release
... Omit many places ...
Example Three:
# _*_coding:utf-8_*_ Import threading from time import sleep, CTime "" "" "" "" "" "" "" "" The Process "" have mode of Thread "" "_time = [2,4,6,8] # Thread Hang Time thread suspend _maxlink = Len (_time) # A pool of thread max-link thread pool Maximum number _thread_pool = [] # a P  Ool of thread that save instantiation threads thread pool to hold threads instance # a pool of thread def loop (index, time): "" "a function  To class Thread for sleep some times "" Print start loop%s at: "% index, CTime () (Time[index)) print ' End loop%s ' at:% index, CTime () def thread_pool (*arg): "" "A function of that create and save instantiation O F Threading to thread Pool "" "Func, LN, time = arg for I in range (LN): t = Threading.
    Thread (Target=func, args= (i, Time)) T.setdaemon (True) _thread_pool.append (t) def Thread_start (ARG):

    "" A function that is represents a thread of control. "" " For I in range (ARG): _thread_pool[i].start () to I in range (ARG): _thread_pool[i].join() def main (): "" "" A Function of main "" print "process start at:". Upper (), CTime () Thread_pool (Loop, _maxli NK, _time) Thread_start (_maxlink) print "Process end at:". Upper (), CTime () If __name__ = ' __main__ ': Main ( )
The results of the operation are as follows:
PROCESS START at:  Fri Apr 11:27:32 2017
start loop 0 at:  Fri Apr 11:27:32 2017
START Loop 1 at:  Fri Apr 11:27:32 2017
start loop 2 at:  Fri Apr 11:27:32 2017
start Loop 3 at:  Fri Apr 28 11:27:32 2 017 End
Loop 0 at:  Fri Apr 11:27:34 2017 end
Loop 1 at:  Fri Apr 11:27:36 2017 end
Loop 2 at :  Fri Apr 11:27:38 2017 end
Loop 3 at:  Fri Apr 11:27:40 2017 PROCESS end at
:  Fri Apr 28 11: 27:40 2017
The source code for the Run method is as follows:

method Two . Create an instance of thread and pass it to a callable class object as described earlier about the Start method, and finally the Run method runs the incoming threading. The function function,function of the thread instance is assigned to Self__target, and then the function call is executed in the Run method , in order to implement method two, pass in the class, implement the multithreading call, You must make the instance that is instantiated by the class callable (defining _call_ special methods), you can think of the instantiation of two objects, one is threading. The instantiated object of thread (this instance object can be invoked), one is the instantiated object of the incoming class, and the Run method source code is reviewed again.

def run (self):

        try:
            if Self.__target:
                self.__target (*self.__args, **self.__kwargs)
        finally:
            Del Self.__target, Self.__args, Self.__kwargs
Example four:
# _*_coding:utf-8_*_ Import threading from time import sleep, CTime "" A example for pass a class to the class Thread "" "_time = [2, 4, 6, 8] # thread Hang time thread hangs the maximum number of times _maxlink = Len (_time) # A Pool of thread max-link thread pool _thread_poo L = [] # A pool of thread that save instantiation threads the thread pool class Mythreadfunc (object) that holds the threads instance: "" A callable CLA SS after instantiated "" "Def __init__ (self, _func=none, _name=none, _args=none): Self._func = _func SE Lf._name = _name Self._args = _args def __call__ (self): # Allow instantiated objects to invoke Self.res = Self._func (*s Elf._args def Loop (_index, _time): "" "A function to class Thread for sleep some times" "print" Start loop% 
    S at: '% _index, CTime (_time[_index]) print ' End loop%s at:% _index, CTime () def thread_pool (*arg):
    "" A function that is create and save instantiation of threading to Thread pool "" _func, _ln, _time = arg
 For I in Range (_LN):       t = Threading.
    Thread (Target=mythreadfunc (_func, _func.__name__, (I, _time)) _thread_pool.append (t) def Thread_start (_arg):
    "" A function that is represents a thread of control. "" " For I in Range (_arg): _thread_pool[i].start () to I in Range (_arg): _thread_pool[i].join () def main (
    : "" "A Function of main" "print" process start at: ". Upper (), CTime () Thread_pool (Loop, _maxlink, _time) Thread_start (_maxlink) print "Process end at:". Upper (), CTime () if __name__ = = ' __main__ ': Main ()
The results of the operation are as follows:
PROCESS START at:  Fri Apr 12:20:01 2017
start loop 0 at:  Fri Apr 12:20:01 2017
START Loop 1 at:  Fri Apr 12:20:01 2017
start loop 2 at:  Fri Apr 12:20:01 2017
start Loop 3 at:  Fri Apr 28 12:20:01 2 017 End
Loop 0 at:  Fri Apr 12:20:03 2017 end
Loop 1 at:  Fri Apr 12:20:05 2017 end
Loop 2 at :  Fri Apr 12:20:07 2017 end
Loop 3 at:  Fri Apr 12:20:09 2017 PROCESS end at
:  Fri Apr 28 12: 20:09 2017
Example Five:

method Iii. derive a subclass from thread, create an instance of this subclass, override the Run method

# _*_coding:utf-8_*_
import threading from time
import Sleep,ctime

<
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.