Python Threading Module 2

Source: Internet
Author: User

Thread is one of the most important classes in the threading module and can be used to create threads. There are two ways to create a thread: One is to override its run method by inheriting the thread class, and the other is to create a threading. The thread object in which the callable object is passed in as a parameter in its initialization function (__INIT__). The following examples are illustrated separately. Let's take a look at inheriting threading. Thread class to create a threading example:

#CODING=GBKImportthreading, Time, Randomcount=0classCounter (Threading. Thread):def __init__(self, Lock, threadname):" "@summary: Initializes the object.        @param Lock: Object.        @param threadname: Thread name. " "Super (Counter, self).__init__(name =threadname) Self.lock=LockdefRun (self):" "@summary: Overrides the parent class run method, which executes code within the method after the thread is started. " "        GlobalCount Self.lock.acquire () forIinchXrange (10000): Count= Count + 1self.lock.release () lock=Threading. Lock () forIinchRange (5): Counter (lock,"thread-"+str (i)). Start () Time.sleep (2)#ensure that threads are executedPrintCount

In the code, we created a counter class that inherits the threading. Thread. The initialization function receives two parameters, one is a trivial object and the other is the name of the thread. In counter, the Run method inherited from the parent class is overridden, and the Run method increments one global variable by 10000. In the following code, five counter objects are created, calling their Start method, respectively. Finally prints the result. Here's a description of the Run method and the Start method: They are all inherited from thread, and the run () method executes after the thread is opened, and can write related logic to the Run method (usually called the Run method activity [ Activity]. ); the start () method is used to start the thread.

The second method:

Importthreading, Time, Randomcount=0lock=Threading. Lock ()defDoadd ():" "@summary: Increments the global variable count by 10000. " "    Globalcount, lock Lock.acquire () forIinchXrange (10000): Count= Count + 1lock.release () forIinchRange (5): Threading. Thread (Target= Doadd, args = (), name ='thread-'+str (i)). Start () Time.sleep (2)#ensure that threads are executedPrintCount

In this code, we define the method Doadd, which increments the global variable count by 10000. It then creates 5 thread objects, passes the function object Doadd as a parameter to its initialization function, and then invokes the start method of the Thread object, which executes the Doadd function after the thread starts. It is necessary to introduce threading. Initialization function prototypes for the thread class:
def __init__ (self, group=none, Target=none, Name=none, args= (), kwargs={})
The parameter group is reserved for future expansion;
The parameter target is a callable object (also known as an active [activity]) that executes after the thread is started;
The parameter name is the name of the thread. The default value is "Thread-n" and N is a number.
The parameter args and Kwargs each represent the argument list and the keyword argument when the target is called.

The thread class also defines the following common methods and properties:

Thread.getname ()
Thread.setname ()
Thread.Name

Used to get and set the name of the thread.

Thread.ident

Gets the identifier of the thread. The thread identifier is a non-0 integer that is valid only after the start () method is called, otherwise it only returns none.

Thread.is_alive ()
Thread.isalive ()

Determines whether the thread is active (alive). The thread is active from the time the start () method is called, until the Run () method finishes executing or encounters an unhandled exception.

Thread.Join ([timeout])

Calling Thread.Join will cause the thread to block until the calling thread finishes running or times out. The parameter timeout is a numeric type that indicates the time-out period, and if the parameter is not supplied, the thread will block until the thread ends. Here's an example of how join () is used:

Importthreading, timedefdowaiting ():Print 'Start Waiting:', Time.strftime ('%h:%m:%s') Time.sleep (3)    Print 'Stop Waiting', Time.strftime ('%h:%m:%s') Thread1= Threading. Thread (target =dowaiting) Thread1.start () Time.sleep (1)#Make sure thread thread1 is startedPrint 'start Join'Thread1.join ()#will be blocked until the end of the Thread1 run. Print 'End Join'

Threading. Rlock and Threading.lock

In the threading module, two types of locks are defined: threading. Lock and Threading.rlock. There is a slight difference between them, by comparing the following two sections of code to illustrate:

Import= Threading. Lock ()    #Lock Object lock.acquire  () lock.acquire ()# generates a deadlock.  lock.release () lock.release ( )
Import= Threading. Rlock ()  #rlock Object rlock.acquire () rlock.acquire ()    #  Within the same thread, the program does not clog.  rlock.release () rlock.release ( )

The main difference between these two types of locks is that Rlock allows multiple acquire in the same thread. But lock does not allow this situation. Note: If you use Rlock, then acquire and release must appear in pairs, that is, call n times acquire, must call N times release to really release the occupied locks.

Question: Lock to lock to lock so many times in the end is for what???

Python Threading Module 2

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.