Document directory
- Thread. ident
- Thread. Join ([timeout])
- Condition. Wait ([timeout]):
- Condition. condition y ():
- Event. Wait ([timeout])
- Event. Set ()
- Event. Clear ()
- Event. isset ()
- Threading. enumerate ()
- Threading. settrace (func)
- Threading. setprofile (func)
Previous
I introduced the thread module. Today I want to learn another module of the python operating thread: threading. Threading provides more convenient APIs to operate threads by secondary encapsulation of the thread module. Today, I have a lot of content, but I have to talk less about it. Now I will start to get started!
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 = GBK <br/> Import threading, time, random <br/> COUNT = 0 <br/> class counter (threading. thread): <br/> def _ init _ (self, lock, threadname): <br/> ''' @ Summary: initialization object. </P> <p> @ Param lock: the object to be deleted. <Br/> @ Param threadname: Specifies the thread name. <Br/> ''' <br/> super (counter, self ). _ init _ (name = threadname) # Note: You must explicitly call the initialization function of the parent class <br/>. <Br/> self. lock = Lock </P> <p> def run (Self): <br/> ''' @ Summary: override the parent class run method, run the code in this method after the thread starts. <Br/> ''' <br/> global count <br/> self. lock. acquire () <br/> for I in xrange (10000): <br/> COUNT = count + 1 <br/> self. lock. release () <br/> lock = threading. lock () <br/> for I in range (5): <br/> counter (lock, "thread-" + STR (I )). start () <br/> time. sleep (2) # Make sure all threads have been executed <br/> 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. Here we want to explainRun Method
AndStart method:
They are all 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, random <br/> COUNT = 0 <br/> lock = threading. lock () <br/> def doadd (): <br/> ''' @ Summary: increase the global variable count by 10000 one by one. <Br/> ''' <br/> global count, lock <br/> lock. acquire () <br/> for I in xrange (10000): <br/> COUNT = count + 1 <br/> lock. release () <br/> for I in range (5): <br/> threading. thread (target = doadd, argS = (), name = 'thread-'+ STR (I )). start () <br/> time. sleep (2) # Make sure all threads have been executed <br/> 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, time <br/> def dowaiting (): <br/> Print 'start waiting: ', time. strftime ('% H: % m: % s') <br/> time. sleep (3) <br/> Print 'Stop waiting', time. strftime ('% H: % m: % s') <br/> thread1 = threading. thread (target = dowaiting) <br/> thread1.start () <br/> time. sleep (1) # Make sure that thread thread1 has been started <br/> Print 'start join' <br/> thread1.join () # It will be blocked until thread1 stops running. <Br/> 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 threading <br/> lock = threading. Lock () # Lock Object <br/> lock. Acquire () <br/> lock. Acquire () # generates a deadlock. <Br/> lock. Release () <br/> lock. Release ()
Import threading <br/> rlock = threading. rlock () # rlock object <br/> rlock. acquire () <br/> rlock. acquire () # In the same thread, the program will not be blocked. <Br/> rlock. Release () <br/> 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. policy_all ()
Condition. policyall ()
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 <br/> # ---- hide-and-seek games <br/> Import threading, time <br/> class hider (threading. thread): <br/> def _ init _ (self, Cond, name): <br/> super (hider, self ). _ init _ () <br/> self. cond = cond <br/> self. name = Name </P> <p> def run (Self): <br/> time. sleep (1) # Make sure to first run the method in seeker </P> <p> self. cond. acquire () # B <br/> Print self. name + ': I have blindfolded' <br/> self. cond. policy () <br/> self. cond. wait () # C <br/> # F <br/> Print self. Name + ': I found you ~ _~ '<Br/> self. cond. policy () <br/> self. cond. release () <br/> # G <br/> Print self. name + ': I won' # H </P> <p> class seeker (threading. thread): <br/> def _ init _ (self, Cond, name): <br/> super (Seeker, self ). _ init _ () <br/> self. cond = cond <br/> self. name = Name <br/> def run (Self): <br/> self. cond. acquire () <br/> self. cond. wait () # A # Release the occupation of TSL, And the thread is suspended here until it is reset by TSL. <br/>. <Br/> # D <br/> Print self. name + ': I have hidden it. Come and find me.' <br/> self. cond. policy () <br/> self. cond. wait () # E <br/> # H <br/> self. cond. release () <br/> Print self. name + ': you have found it ~~~ '</P> <p> cond = threading. condition () <br/> seeker = seeker (Cond, 'seeker') <br/> hider = hider (Cond, 'er er') <br/> seeker. start () <br/> 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 <br/> # ---- hide-and-seek games <br/> Import threading, time <br/> class hider (threading. thread): <br/> def _ init _ (self, Cond, name): <br/> super (hider, self ). _ init _ () <br/> self. cond = cond <br/> self. name = Name </P> <p> def run (Self): <br/> time. sleep (1) # Make sure to run the method in seeker </P> <p> Print self. name + ': I have blindfolded' </P> <p> self. cond. set () </P> <p> time. sleep (1) </P> <p> self. cond. wait () <br/> Print self. na Me + ': I found you ~ _~ '</P> <p> self. cond. set () </P> <p> Print self. name + ': I won' </P> <p> class seeker (threading. thread): <br/> def _ init _ (self, Cond, name): <br/> super (Seeker, self ). _ init _ () <br/> self. cond = cond <br/> self. name = Name <br/> def run (Self): <br/> self. cond. wait () </P> <p> Print self. name + ': I have hidden it. Come and find me.' <br/> self. cond. set () </P> <p> time. sleep (1) <br/> self. cond. wait () </P> <p> Print self. name + ': found by you Here you are ~~~ '</P> <p> cond = threading. event () <br/> seeker = seeker (Cond, 'secret') <br/> hider = hider (Cond, 'er er') <br/> seeker. start () <br/> 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 (): <br/> Print "Hello, world" <br/> T = timer (3, hello) <br/> T. start () # execute the hello function 3 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 contains a lot of content. It is difficult to write a full article. For more information about the threading module, please refer to the python manual threading.
Module.