The basic idea of using the Python module threading to write multithreaded routines is to threading. The thread class derives a subclass from it, implements the business logic in the run function of the subclass, creates a thread pool of the subclass object, and executes the execution function of the subclass object.
Here is an example of multithreaded programming using the threading module in Python, in which we create a thread pool and a shared counter for 4 threads, and then let each thread preempt execution by 1 and then hibernate. This is equivalent to give a two-dimensional space, the number of threads is one-dimensional, the total number of times per thread is another dimension, from the following running results can be easily seen: the situation of the thread polling scheduling.
Note that here the print output for count needs to be included inside the mutex, otherwise the printout is incorrect.
Source Code implementation:
#!/usr/bin/env python
#encoding: utf-8
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 ()
Print ThreadName, X, Count
count = count + 1
mutex.release ()
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 ()
Run Effect chart: