Python supports multiple threads and native threads. It is mainly implemented through the thread and threading modules. Thread is a relatively underlying module, and threading is encapsulated for thread, which can be used more conveniently. Here, we need to mention that python does not fully support threads and cannot use multiple CPUs. However, we have considered improving this in the next version of Python. Let's wait and see.
The threading module is mainly used to visualize some thread operations and creates a class called thread. Generally, there are two ways to use a thread. One is to create a function to be executed by the thread, and pass the function into the thread object for execution; the other is to inherit from the thread directly, create a new class, and put the code executed by the thread into this new class. Let's take a look at these two methods.
#-*-Encoding: gb2312 -*-
Import string, threading, time
Def thread_main ():
Global count, mutex
# Obtain the thread name
Threadname = threading. currentthread (). getname ()
For X in xrange (0, INT ()):
# Getting a lock
Mutex. Acquire ()
Count = count + 1
# Release a 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 ()
# Create a thread object first
For X in xrange (0, num ):
Threads. append (threading. Thread (target = thread_main, argS = (10 ,)))
# Start all threads
For T in threads:
T. Start ()
# Wait for all sub-threads to exit in the main thread
For T in threads:
T. Join ()
If _ name _ = '_ main __':
Num = 4
# Create 4 threads
Main (4)
The above is the first practice, which is very common. The following is another practice. Friends who have used Java should be familiar with this mode:
#-*-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 a lock
Mutex = threading. Lock ()
# Create a thread object
For X in xrange (0, num ):
Threads. append (test (10 ))
# Start a thread
For T in threads:
T. Start ()
# Wait until the sub-thread ends
For T in threads:
T. Join ()