1. Create threading.Thread object to realize multithreading:
Create a threading.Thread object and pass the callable object as a parameter in its initialization function (_init_)
Introduce threadring to play music and video at the same time:
#coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print ("I was listening to %s. %s\n" %(func,ctime())) sleep(1) def move(func): for i in range(2): print ("I was at the %s! %s\n" %(func,ctime())) sleep(5) threads = [] t1 = threading.Thread(target=music,args=(u'Love Business',)) threads.append(t1) t2 = threading.Thread(target=move,args=(u'Avatar',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() print ("all over %s" %ctime())
import threading
First import threading module, which is the premise of using multithreading.
threads = []
t1 = threading.Thread(target=music,args=(u'love deal',)
threads.append(t1)
Theads array is created, thread t1 is created, threading.Thread() method is used, in which music method target=music is called, and music is passed by args method. Install the created thread t1 into the threads array.
The thread t2 is then created in the same way and loaded into the threads array.
for t in threads:
t.setDaemon(True)
t.start()
Finally, the array is traversed through a for loop. (Arrays are loaded with t1 and t2 threads)
setDaemon()
setDaemon(True) declares a thread as a daemon thread, which must be set before the start() method call. If it is not set as a daemon thread, the program will be suspended indefinitely. When the child thread starts, the parent thread continues to execute. When the parent thread finishes executing the last statement print "all over% s"% CTime (), it exits without waiting for the child thread, and the child thread ends at the same time.
start()
Start thread activity.
Operation results:
>>> ========================= RESTART ================================ >>> I was listening to Love Business. Thu Apr 17 12:51:45 2014 I was at the Avatar! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014
From the result of execution, the sub-threads (muisc, move) and the main threads (print "all over% s"% ctime()) start at the same time, but the sub-threads also terminate because the main threads finish executing.
Continue to adjust procedures:
... if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join() print "all over %s" %ctime()
We only add a join() method to the above program to wait for the thread to terminate. The function of join() is that the parent thread of the child thread will be blocked until the child thread has finished running.
Note: The join() method is located outside the for loop, which means that the main process must wait until both processes in the for loop are finished.
Operation results:
>>> ========================= RESTART ================================ >>> I was listening to Love Business. Thu Apr 17 13:04:11 2014 I was at the Avatar! Thu Apr 17 13:04:11 2014 I was listening to Love Business. Thu Apr 17 13:04:12 2014 I was at the Avatar! Thu Apr 17 13:04:16 2014 all over Thu Apr 17 13:04:21 2014
As can be seen from the execution results, music and move are started at the same time.
The start time is 4 minutes and 11 seconds until the main process is called in 4 minutes and 22 seconds, which takes 10 seconds. We can adjust music's sleep() time to 4 seconds by reducing it by 2 seconds from a single thread.
... def music(func): for i in range(2): print "I was listening to %s. %s" %(func,ctime()) sleep(4) ...
Implementation results:
>>> ====================== RESTART ================================ >>> I was listening to Love Business. Thu Apr 17 13:11:27 2014 I was at the Avatar! Thu Apr 17 13:11:27 2014 I was listening to Love Business. Thu Apr 17 13:11:31 2014 I was at the Avatar! Thu Apr 17 13:11:32 2014 all over Thu Apr 17 13:11:37 2014
Subthread starts 11 minutes 27 seconds, main thread runs 11 minutes 37 seconds.
Although music extends from 1 second to 4 songs per song, the total time for running scripts in a multi-way way way remains unchanged.
2. Implementing multithreading by inheriting Thread class
Examples are given below. Let's start with an example of creating threads by inheriting the threading.Thread class:
#coding=utf-8 import threading, time count = 0 class Counter(threading.Thread): def __init__(self, lock, threadName): ''' @summary: Initialize the object. @param lock: Trivial objects. @param threadName: Thread name. ''' super(Counter, self).__init__(name = threadName) #Note: Be sure to explicitly call the initialization function of the parent class. self.lock = lock def run(self): ''' @summary: Rewrite parent class run Method, the code in this method is executed after the thread is started. ''' global count self.lock.acquire() for i in range(10000): count = count + 1 self.lock.release() lock = threading.Lock() for i in range(5): Counter(lock, "thread-" + str(i)).start() time.sleep(2) #Ensure that all threads are executed print (count)
In the code, we create a Counter class that inherits threading.Thread. Initialization function receives two parameters, one is trivial object, the other is the name of the thread. In Counter, the run method inherited from the parent class is rewritten, and the run method adds 10,000 global variables one by one. In the following code, five Counter objects are created and their start methods are invoked. Finally, print the result. Here we will explain the run method and start method: they are inherited from Thread. The run() method executes after the thread is opened, and can write the relevant logic into the run method; the start() method is used to start the thread.
3.Thread class
The Thread class also defines the following common methods and attributes:
Thread.getName()
Thread.setName()
Thread.name
Used to get and set the name of the thread.
Thread.ident
Gets the thread identifier. The thread identifier is a non-zero integer, which is valid only after the start() method is called, otherwise it only returns None.
Thread.is_alive()
Thread.isAlive()
Determine whether the thread is alive. Threads are activated during the period from calling the start() method to executing the run() method or interrupting when an unhandled exception occurs.
Thread.join([timeout])
Calling Thread.join will block the main thread until the called thread runs out or times out. The parameter timeout is a numerical type that represents 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 illustrates the use of join():
import threading, time def 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 thread1 is started print ('start join') thread1.join() #It will be blocked until thread1 runs out. print ('end join')
Theading.RLock and threading.Lock
In threading module, two types of triviality are defined: threading.Lock and threading.RLock. There is a slight difference between them, which is illustrated by comparing the following two pieces of code:
import threading lock = threading.Lock() #Lock object lock.acquire() lock.acquire() #It produces triviality. lock.release() lock.release()
import threading rLock = threading.RLock() #RLock object rLock.acquire() rLock.acquire() #In the same thread, the program will not block. rLock.release() rLock.release()
The main difference between these two trivialities is that RLock allows multiple acquisitions in the same thread. Lock does not allow this. Note: If RLock is used, acquire and release must appear in pairs, that is, n acquires are invoked, and N releases must be invoked in order to truly release the triviality occupied.
threading.Condition
Conditions can be understood as a high-level triviality, which provides more advanced functions than Lock and RLock, allowing us to control complex thread synchronization problems. threadiong.Condition maintains a trivial object internally (RLock by default), which can be passed in as a parameter when creating a Condition object. Condition also provides acquire and release methods, which have the same meaning as trivial acquire and release methods. In fact, it simply calls the corresponding methods of trivial internal objects. Condition also provides the following methods (note in particular: these methods can only be invoked after taking up trivial (acquire) or they will be reported as Runtime Error exceptions. ):
Condition.wait([timeout]):
The wait method releases the internal overhead while the thread is suspended until the notification is awakened or timed out (if a timeout parameter is provided). When the thread is awakened and re-occupied, the program will continue to execute.
Condition.notify():
Wake up a suspended thread (if a suspended thread exists). Note: The notify() method does not release the triviality involved.
Condition.notify_all()
Condition.notifyAll()
Wake up all suspended threads (if there are suspended threads). Note: These methods do not release the triviality.
Now write a hide-and-seek game to introduce the basic use of threading.Condition. Suppose the game is played by two people, a Hider and a Seeker. The rules of the game are as follows: 1. After the game starts, Seeker blindfolds himself first and notifies Hider after blindfolding; 2. Hider receives the notification and starts to find a place to hide himself. After hiding, he notifies Seeker that he can find it; 3. Seeker begins to find Hider after receiving the notification. Hider and Seeker are both independent individuals. They are represented by two separate threads in the program. During the game, there is a certain temporal relationship between their behavior. We control this temporal relationship through Conditions.
#---- Condition #The game of hide-and-seek import threading, time class Hider(threading.Thread): def __init__(self, cond, name): super(Hider, self).__init__() self.cond = cond self.name = name def run(self): time.sleep(1) #Ensure that methods in Seeker are run first self.cond.acquire() #b print (self.name + ': I've blindfolded my eyes.') 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.') #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 trivial occupancy, while threads hang here until notify and re-occupy triviality. #d print (self.name + ': I've already hidden it. Come and find me.') self.cond.notify() self.cond.wait() #e #h self.cond.release() print (self.name + ': You found it. Ouch.~~~') cond = threading.Condition() seeker = Seeker(cond, 'seeker') hider = Hider(cond, 'hider') seeker.start() hider.start()
threading.Event
Event implements functions similar to Condition, but a little simpler than Condition. It achieves synchronization between threads by maintaining internal identifiers. (The System.Threading.ManualResetEvent classes in threading.Event and. NET implement the same functionality.)
Event.wait([timeout])
Block the thread until the internal identifier of the Event object is set to True or timeout (if the parameter timeout is provided).
Event.set()
Set the identity bit to Ture
Event.clear()
Set the logo to False.
Event.isSet()
Determine whether the identifier bit is Ture.
Next, use Event to play hide-and-seek (maybe Event is not a very good image)
#---- Event #The game of hide-and-seek import threading, time class Hider(threading.Thread): def __init__(self, cond, name): super(Hider, self).__init__() self.cond = cond self.name = name def run(self): time.sleep(1) #Ensure that methods in Seeker are run first print (self.name + ': I've blindfolded my eyes.') self.cond.set() time.sleep(1) self.cond.wait() print (self.name + ': I found you. ~_~') self.cond.set() print (self.name + ': I won.') 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 already hidden it. Come and find me.') self.cond.set() time.sleep(1) self.cond.wait() print (self.name + ': You found it. Ouch.~~~') cond = threading.Event() seeker = Seeker(cond, 'seeker') hider = Hider(cond, 'hider') seeker.start() hider.start()
threading.Timer
Theading. Timer is a subclass of threading.Thread that can perform an operation after a specified time interval. Here's an example from the Python Manual:
def hello(): print ("hello, world") t = Timer(3, hello) t.start() # Three seconds later, the hello function is executed.
The commonly used methods of threading are:
threading.active_count()
threading.activeCount()
Gets the number of active threads that are currently active.
threading.current_thread()
threading.currentThread()
Gets the current Thread object.
threading.enumerate()
Gets a list of all current active threads.
threading.settrace(func)
Set up a trace function to be called before run() executes.
threading.setprofile(func)
Set up a trace function to be called after run() has been executed.
The threading module has a lot of content, more can be referred to the official. Poke here!