Python multithreaded programming (ii) : two ways to start threads

  • 2020-05-05 11:25:43
  • OfStack

In Python, we mainly implemented thread and threading modules, Python threading module is some packaging for thread, which can be more convenient to be used, so we use threading module to achieve multi-threaded programming. 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.

passes the function into Thread object


''' 
Created on 2012-9-5 
 
@author:  walfred
@module: thread.ThreadTest1 
@description:
'''   
import threading 
 
def thread_fun(num): 
    for n in range(0, int(num)): 
        print " I come from %s, num: %s" %( threading.currentThread().getName(), n) 
 
def main(thread_num): 
    thread_list = list(); 
    # Create the thread object first  
    for i in range(0, thread_num): 
        thread_name = "thread_%s" %i 
        thread_list.append(threading.Thread(target = thread_fun, name = thread_name, args = (20,))) 
 
    # Start all threads     
    for thread in thread_list: 
        thread.start() 
 
    # Waits for all child threads in the main thread to exit  
    for thread in thread_list: 
        thread.join() 
 
if __name__ == "__main__": 
    main(3)

The program started three threads, and printed the name of each thread, this is relatively simple, to deal with the repeated task is used, the following is the way to use threading inheritance;

inherits from threading.Thread class


'''
Created on 2012-9-6
 
@author: walfred
@module: thread.ThreadTest2
''' 
 
import threading 
 
class MyThread(threading.Thread): 
    def __init__(self): 
        threading.Thread.__init__(self); 
 
    def run(self): 
        print "I am %s" %self.name 
 
if __name__ == "__main__": 
    for thread in range(0, 5): 
        t = MyThread() 
        t.start()

In the following articles, I will show you how to control these threads, including the exit of the child thread, whether the child thread survives, and setting the child thread to the daemon thread (Daemon).


Related articles: