Python multi-thread programming (2): two ways to start a thread: python multi-thread programming
In Python, we mainly implement the thread and threading modules. The threading module of Python is encapsulated for thread and can be used more conveniently, therefore, we use the threading module to implement multi-threaded 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
Copy codeThe 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
Copy codeThe 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 ).