This article mainly introduces Python multi-Thread programming (1): two methods for starting a Thread. This article describes how to pass functions into a Thread object and inherit from threading. there are two methods for Thread. if you need them, you can refer to the two modules thread and threading in Python, among them, the threading module of Python is packaged for thread and can be used more conveniently. Therefore, we use the threading module to implement multi-thread programming. 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.
Pass the function to the Thread object
The code is as follows:
'''
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 a 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 ()
# Wait for all sub-threads to exit in the main thread
For thread in thread_list:
Thread. join ()
If _ name _ = "_ main __":
Main (3)
The program starts three threads and prints the name of each thread. this is simple. it is useful to process repeated tasks. The following describes how to inherit threading;
Inherited from threading. Thread class
The code is as follows:
'''
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 ()
The next article will introduce how to control these threads, including the exit of the sub-thread, whether the sub-thread is alive, and set the sub-thread as the Daemon ).