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 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 =gbkimport threading, time, Randomcount = 0class Counter (threading. Thread): Def __init__ (self, Lock, threadname): "' @summary: Initialize the object. @param Lock: Object. @param threadname: Thread name. " super (Counter, self)." __init__ (name = threadname) #注意: Be sure to explicitly call the initialization function of the parent class. Self.lock = Lock def run (self): @summary: Overrides the parent class run method and executes the code within the method after the thread is started. " 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) #确保线程都执行完毕print count
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, which can write the relevant logic into the Run method (usually called the Run method active [activity]. ); the start () method is used to start the thread.
And look at another way to create a thread:
Import threading, time, Randomcount = 0lock = Threading. Lock () def doadd (): "@summary: Increments the global variable count by 10000. "Global count, lock Lock.acquire () for I in Xrange (10000): count = count + 1 lock.release () for I in range (5): Threa Ding. Thread (target = doadd, args = (), name = ' thread-' + str (i)). Start () Time.sleep (2) #确保线程都执行完毕print count
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:
Import threading, Timedef dowaiting (): print ' Start waiting: ', Time.strftime ('%h:%m:%s ') time.sleep (3) print ' Stop waitin G ', Time.strftime ('%h:%m:%s ') Thread1 = threading. Thread (target = dowaiting) Thread1.start () time.sleep (1) #确保线程thread1已经启动print ' start join ' Thread1.join () #将一直堵塞, 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 Threadinglock = Threading. Lock () #Lock对象lock. Acquire () Lock.acquire () #产生了死琐. Lock.release () lock.release () Import Threadingrlock = Threading. Rlock () #RLock对象rLock. Acquire () Rlock.acquire () #在同一线程内, 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.
Threading. Condition
Condiftion can be understood as a high-level lock, which provides more advanced functionality than locks, Rlock allows us to control complex thread synchronization issues. Threadiong. Condition maintains a trivial object internally (by default, Rlock), which can be passed in as a parameter when creating a Condigtion object. Condition also provides acquire, release method, its meaning and the acquire, release method consistent, in fact, it is simply a simple call inside the corresponding method of the object. Condition also provides the following methods (especially note: These methods can only be called after the acquire), otherwise the runtimeerror exception will be reported. ):
Condition.wait ([timeout]):
The Wait method releases the internal footprint, and the thread is suspended until the notification is woken up or timed out (if the timeout parameter is provided). The program will continue to execute when the thread is awakened and re-occupied.
Condition.notify ():
Wakes up a suspended thread (if there is a pending thread). Note: the Notify () method does not release the occupied locks.
Condition.notify_all ()
Condition.notifyall ()
Wakes all pending threads (if there are pending threads). Note: These methods do not release the locks that are occupied.
Now write a game of hide and seek to specifically introduce threading. Basic use of condition. Let's say this game is played by two people, one (Hider), one for (Seeker). The rules of the game are as follows: 1. After the game began, seeker first blindfolded his eyes, blindfolded, on the notice hider;2. Hider receive notice after the beginning to find a place to hide himself, hide well, then notify Seeker can find; 3. Seeker received the notice, began to find Hider. Hider and seeker are independent individuals, using two separate threads in the process to indicate that there is a temporal relationship between the actions of the two in the course of the game, and we control the timing relationship through the condition.
#----condition#----hide and seek game 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) #确保先运行Seeker中的方法 self.cond.acquire () #b print Self.name + ': I've got my eyes covered ' self.cond.notify () self . cond.wait () #c #f print Self.name + ': I found you. ~_~ ' Self.cond.notify () self.cond.release () #g print self. Name + ': I won the ' #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 #释放对琐的占用, while the thread hangs here until it is notify and re-occupied. #d print Self.name + ': I've hidden it, you come to Me ' self.cond.notify () self.cond.wait () #e #h self.cond.release () Print sel F.name + ': You have found, Ay ~ ~ ~ ~ ~ ~ ~ Cond = Threading. Condition () Seeker = Seeker (cond, ' seeker ') Hider = Hider (cond, ' Hider ') Seeker.start () Hider.start () threading. Event
The event implements functions similar to condition, but is a little simpler than condition. It implements synchronization issues between threads by maintaining internal identifiers. (Threading. Event and the System.Threading.ManualResetEvent class in. NET implement the same functionality. )
Event.wait ([timeout])
The thread is blocked until the event object's internal identity bit is set to true or timed out (if parameter timeout is provided).
Event.set ()
Set the identity bit to ture
Event.clear ()
Set the identity companion to False.
Event.isset ()
Determines whether the identity bit is ture.
The following uses the event to implement the game of hide and seek (may use event to achieve not very image)
#----event#----hide and seek game 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) #确保先运行Seeker中的方法 print Self.name + ': I've got my eyes covered ' 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've hidden it, you come find Me ' self.cond.set () Time.sleep (1) self.cond.wait () print Self.name + ': You've found it, eh ~ ~ ~ ~ ~ ~ ' cond = Threading. Event () Seeker = Seeker (cond, ' seeker ') Hider = Hider (cond, ' Hider ') Seeker.start () Hider.start () threading. Timer
Threading. A timer is a subclass of Threading.thread that can perform an action after a specified interval of time. Here is an example from the Python manual:
def hello (): print "Hello, world" T = Timer (3, Hello) T.start () # 3 seconds after executing the Hello function.
There are some common methods in the threading module that do not introduce:
Threading.active_count ()
Threading.activecount ()
Gets the number of currently active (alive) threads.
Threading.current_thread ()
Threading.currentthread ()
Gets the current thread object (thread object).
Threading.enumerate ()
Gets a list of all currently active threads.
Threading.settrace (func)
Sets a trace function to be called before run () executes.
Threading.setprofile (func)
Set up a trace function to be called after run () has finished executing.
Threading module of a lot of content, an article is difficult to write full, more information about the threading module, please consult the Python manual threading module.