Several common methods of threading module in Python are illustrated.

Source: Internet
Author: User
This article mainly introduces several common methods of threading module in Python. using threading module to create and operate Threads is an important knowledge in Python learning. For more information, see Threading. Thread

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 inherit the Thread class and override its run method; the other is to create a threading. thread object. in its initialization function (_ init _), the object can be called as a parameter. The following are examples. Let's take a look at the example of creating a Thread by inheriting the threading. Thread class:

# Coding = gbkimport threading, time, randomcount = 0 class Counter (threading. thread): def _ init _ (self, lock, threadName): ''' @ summary: Initialization object. @ Param lock: the object to be deleted. @ Param threadName: specifies the thread name. '''Super (Counter, self). _ init _ (name = threadName) # Note: You must explicitly call the initialization function of the parent class. Self. lock = lock def run (self): ''' @ summary: rewrite the run method of the parent class and run the code in the method after the thread starts. '''Global count self. lock. acquire () for I in xrange (10000): count = count + 1 self. lock. release () lock = threading. lock () for I in range (5): Counter (lock, "thread-" + str (I )). start () time. sleep (2) # Make sure all threads have finished running print count

In the code, we create a Counter class that inherits threading. Thread. The initialization function receives two parameters, one being a trivial object and the other being the thread name. In Counter, the run method inherited from the parent class is rewritten. The run method increases the number of global variables by 10000 one by one. In the following code, five Counter objects are created and their start methods are called respectively. Finally, print the result. The run and start methods are inherited from the Thread. the run () method will be executed after the Thread is enabled, you can write the relevant logic to the run method (the run method is usually called the Activity [Activity]); The start () method is used to start a thread.

Let's look at another method to create a thread:

Import threading, time, randomcount = 0 lock = threading. Lock () def doAdd (): ''' @ summary: increase the global variable count by 10000 one by one. '''Global count, lock. acquire () for I in xrange (10000): count = count + 1 lock. release () for I in range (5): threading. thread (target = doAdd, args = (), name = 'thread-'+ str (I )). start () time. sleep (2) # Make sure all threads have finished running print count

In this code, we define the doAdd method, which increases the global variable count by 10000 one by one. Five Thread objects are created, and the function object doAdd is passed as a parameter to its initialization function. then, the start method of the Thread object is called. after the Thread starts, the doAdd function is executed. It is necessary to introduce the initialization function prototype of the threading. Thread class:

def __init__(self, group=None, target=None, name=None, args=(), kwargs={})

  • The group parameter is reserved for future expansion;
  • The target parameter is a Callable object (also called an activity) that is executed after the thread starts;
  • The parameter name is the name of the thread. The default value is "Thread-N", and N is a number.
  • The args and kwargs parameters represent the parameter list and keyword parameters when the target is called, respectively.

The Thread class also defines the following common methods and attributes:

Thread.getName()Thread.setName()Thread.name

Used to obtain and set the thread name.

Thread.ident

Obtains the identifier of a thread. The thread identifier is a non-zero integer. This attribute is valid only after the start () method is called. Otherwise, it returns only None.

Thread.is_alive()Thread.isAlive()

Determines whether the thread is active (alive ). The thread is activated from the time when the start () method is called to start the thread, to the time when the run () method is finished or the thread is interrupted due to an unhandled exception.

Thread.join([timeout])

Calling Thread. join will block the main Thread until the call Thread ends or times out. The timeout parameter is a numeric value that indicates the timeout time. if this parameter is not provided, the main thread will be blocked until the end of the called thread. The following example shows how to use join:

Import threading, timedef doWaiting (): 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 has started print 'start join' thread1. join () # it will remain congested until thread1 stops running. Print 'end join'

Threading. RLock and threading. Lock

The threading module defines two types of cumbersome: threading. Lock and threading. RLock. There is a slight difference between them, which can be explained by comparing the following two pieces of code:

Import threadinglock = threading. Lock () # Lock object lock. acquire () lock. acquire () # generate a deadlock. Lock. release () lock. release () import threadingrLock = threading. RLock () # RLock object rLock. acquire () rLock. acquire () # In the same thread, the program will not be blocked. RLock. release () rLock. release ()

The main difference between the two types of OSS is that RLock allows multiple acquire requests in the same thread. But Lock does not allow this situation. Note: If RLock is used, The acquire and release must appear in pairs. that is, The acquire and release must be called n times to release the occupied space.
Threading. Condition

Condiftion can be understood as an advanced feature. It provides more advanced features than Lock and RLock, allowing us to control complicated thread synchronization problems. Threadiong. Condition maintains a wretched object internally (RLock by default). It can be passed as a parameter when a Condigtion object is created. Condition also provides the acquire and release methods, which have the same meaning as the wretched acquire and release methods. In fact, it is just a simple method to call the corresponding methods of the internal Wretched objects. Condition also provides the following methods (note: these methods can be called only after being occupied by the cumbersome (acquire); otherwise, a RuntimeError exception will be reported .) :
Condition. wait ([timeout]):

The wait method releases the internal occupation and threads are suspended until the received notification is awakened or timed out (if the timeout parameter is provided ). When the thread is awakened and occupied again, the program will continue to run.
Condition. Condition Y ():

Wake up a suspended thread (if a suspended thread exists ). Note: The notify () method does not release the occupied objects.

Condition.notify_all()Condition.notifyAll()

Wake up all suspended threads (if any ). Note: these methods do not release the occupied items.

Now I want to write a game named "hide-and-seek" to introduce the basic usage of threading. Condition. Assume that this game is played by two people, a hidden game and a Seeker ). The rules of the game are as follows: 1. after the game starts, Seeker first glances over his own eyes, and then notifies Hider; 2. after receiving the notification, the Hider starts to find a place to hide it. after hiding it, it notifies the Seeker to find it. 3. after the Seeker receives the notification, it starts to find the Hider. Both Hider and Seeker are independent individuals. they are represented by two independent threads in the program. during the game, the behavior between the two has a certain sequential relationship, we use Condition to control this time series relationship.

# ---- Condition # ---- import threading, timeclass Hider (threading. thread): def _ init _ (self, cond, name): super (Hider, self ). _ init _ () self. cond = cond self. name = name def run (self): time. sleep (1) # Make sure to first run the method self in Seeker. cond. acquire () # B print self. name + ': I have covered my eyes with 'self. cond. policy () self. cond. wait () # c # f print self. name + ': I found you ~ _~ 'Self. cond. policy () self. cond. release () # g print self. name + ': I won' # h class Seeker (threading. thread): def _ init _ (self, cond, name): super (Seeker, self ). _ init _ () self. cond = cond self. name = name def run (self): self. cond. acquire () self. cond. wait () # a # release the occupation of the TSL, and the thread is suspended here until it is destroyed and occupied again. # D print self. name + ': I have hidden it. come and find me.' self. cond. policy () self. cond. wait () # e # h self. cond. release () print self. name + ': you have found it ~~~ 'Cond = threading. Condition () seeker = Seeker (cond, 'Seeker') hider = Hider (cond, 'er er') seeker. start () hider. start ()

Threading. Event

Event implementation is similar to Condition, but it is simpler than Condition. It maintains internal identifiers to implement synchronization between threads. (The threading. Event class and the System. Threading. ManualResetEvent class in. NET implement the same function .)
Event. wait ([timeout])

Blocks the thread until the internal identifier of the Event object is set to True or times out (if the timeout parameter is provided ).
Event. set ()

Set the identification space to true
Event. clear ()

Set the identifier companion to False.
Event. isSet ()

Determine whether the flag is true.

The following uses Event to implement the game of "hide-and-seek" (it may not be very good to use Event)


# ---- Event # ---- import threading, timeclass Hider (threading. thread): def _ init _ (self, cond, name): super (Hider, self ). _ init _ () self. cond = cond self. name = name def run (self): time. sleep (1) # Make sure to run the print self method in Seeker first. name + ': I have covered my eyes with 'self. cond. set () time. sleep (1) self. cond. wait () print self. name + ': I found you ~ _~ 'Self. cond. set () print self. name + ': I won the 'class Seeker (threading. thread): def _ init _ (self, cond, name): super (Seeker, self ). _ init _ () self. cond = cond self. name = name def run (self): self. cond. wait () print self. name + ': I have hidden it. come and find me.' self. cond. set () time. sleep (1) self. cond. wait () print self. name + ': you have found it ~~~ 'Cond = threading. Event () seeker = Seeker (cond, 'Seeker') hider = Hider (cond, 'er er') seeker. start () hider. start ()

Threading. Timer

Threading. Timer is a subclass of threading. Thread. you can perform an operation after the specified interval. The following is an example provided in the Python manual:

Def hello (): print "hello, world" t = Timer (3, hello) t. start () # run the hello function three seconds later.

Some common methods in the threading module are not described:

threading.active_count()threading.activeCount()

Obtains the number of active (alive) threads.

threading.current_thread()threading.currentThread()

Obtains the current Thread object ).

threading.enumerate()

Obtains the list of all active threads.
Threading. settrace (func)

Set a trace function that is called before run () execution.

threading.setprofile(func)

Set a trace function for calling after run () is executed.

The threading module has a lot of content and it is difficult to write a full article,

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.