Introduction to python threading module operating multithreading

  • 2020-05-07 19:56:45
  • OfStack

python is multithreaded and is the thread of native. Mainly through thread and threading modules to achieve. thread is a lower-level module, and threading is a package of thread, which can be used more conveniently. One thing to note here is that python's support for threads isn't perfect enough to take advantage of multiple CPU, but we'll see if we can figure that out in the next version of python.

The       threading module mainly objectifies the operation of some threads, creating class called Thread. 1 generally speaking, there are two modes of using threads. One is to create a function to be executed by the thread, pass the function into the Thread object, and let it execute. The other is to inherit directly from Thread, create a new class, and put the code executed by the thread into the new class. So let's look at these two approaches.


#-*- encoding: gb2312 -*-
import string, threading, time

def thread_main(a):
  global count, mutex
  #  Get the thread name 
  threadname = threading.currentThread().getName()
  
  for x in xrange(0, int(a)):
    #  In 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 1 A lock 
  mutex = threading.Lock()
  #  Create the 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()
  #  Waits for all child threads in the main thread to exit 
  for t in threads:
    t.join() 
  
  
if __name__ == '__main__':
  num = 4
  #  create 4 A thread 
  main(4)

The above is the first practice, which is very common, and the following is another, which should be familiar to those who have used Java:


#-*- 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))
  #  Starting a thread 
  for t in threads:
    t.start()
  #  Wait for the child thread to finish 
  for t in threads:
    t.join() 


Related articles: