Anyone who learns python should know that Python is a thread that supports multithreading and is native. This article is mainly through the thread and threading these two modules to achieve multithreading.
Python's thread module is a relatively low-level module, Python's threading module is a thread to do some packaging, can be more convenient to use.
What you need to mention here is that Python's support for threading is not perfect enough to take advantage of multiple CPUs, but the next version of Python has already been considered to improve this, let's wait and see.
Threading module is mainly for the operation of some threads of the object, the creation of a class called Thread.
In general, there are two modes of using threads, one is to create a function to execute the thread, pass the function into the thread object, let it execute, and the other is to inherit from thread directly, create a new class, and put the code executed by the thread into the new class.
Let's take a look at both of these approaches.
One, Python thread implementation multithreading
#-*-encoding:gb2312-*-import String, threading, Time Def Thread_main (a): global Count, mutex # get thread name Threa Dname = Threading.currentthread (). GetName () for x in xrange (0, Int (a)): # Get lock Mutex.acquire () count = Count + 1 # release lock mutex.release () print ThreadName, x, Count time.sleep (1) def main (num): Global Count, mutex threads = [] count = 1 # Creates a lock mutex = Threading. Lock () # First creates a thread object for x in xrange (0, num): threads.append (Threading. Thread (Target=thread_main, args= ())) # starts all threads for T in Threads: T.start () # Waiting for all child threads to exit in the main thread For T in Threads: t.join () if __name__ = = ' __main__ ': num = 4 # Create 4 threads Main (4)
Second, Python threading realize multithreading
#-*-encoding:gb2312-*-import Threadingimport Time Class Test (threading. Thread): def __init__ (self, num): threading. Thread.__init__ (self) self._run_num = num def run (self): global count, mutex ThreadName = Threading.currentthread (). GetName () for x in xrange (0, int (self._run_num)): mutex.acquire () count = Count + 1 mutex.release () print ThreadName, x, Count time.sleep (1) if __name__ = = ' __main__ ': Global Count, mutex threads = [] num = 4 count = 1 # Create lock Mutex = Threading. Lock () # Create thread object for x in xrange (0, num): threads.append (Test) # Start thread for T in Threads: T.start () # waits for the child thread to end for the T in Threads:
It is believed that the Python multithreaded instance described in this paper can be used for reference in Python programming.