Python supports multithreading and is a native thread. Mainly through the thread and threading these two modules to achieve. Thread is the lower level of the module, threading is the thread made some packaging, can be more convenient to use. One thing to mention here is that Python's support for threads is not perfect enough to take advantage of multiple CPUs, but the next version of Python has been considered to improve this, so let's wait and see.
In the threading module, the main object is the manipulation of some threads, creating a class called Thread. Generally speaking, there are two modes of using threads, one is to create a function to execute the thread, pass it into the thread object, let it execute, the other is to inherit directly from thread, create a new class, and put the thread execution code into this new class. Let's take a look at both of these approaches.
#-*-encoding:gb2312-*-
Import String, threading, Time
def Thread_main (a):
global Count, mutex
# get thread name
threadname = 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
# Create a lock
Mutex = Threading. Lock ()
# First create thread object for
x in xrange (0, num):
threads.append (Threading. Thread (Target=thread_main, args=))
# Start All threads
for T in Threads:
T.start ()
# Wait for all child threads to exit in main thread For
T in Threads:
t.join ()
if __name__ = = ' __main__ ':
num = 4
# Create 4 threads
Main (4)
The above is the first approach, this approach is very common, the following is another, once used Java friends should be familiar with this pattern:
#-*-encoding:gb2312-*-
Import Threading
Import 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 ()
# Wait for child thread end for
T in Threads:
t.join ()