Introduction to multiple threads in the python threading module, pythonthreading
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, timedef thread_main (a): global count, mutex # obtain the thread name threadname = threading. currentThread (). getName () for x in xrange (0, int (a): # obtain the lock mutex. acquire () count = count + 1 # Release the 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 a thread object 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 four 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 threadingimport timeclass 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 the thread for t in threads: t. start () # Wait until the sub-thread ends for t in threads: t. join ()