In Python we are mainly implemented through the thread and threading two modules, where Python's threading modules are packaged for thread and can be used more easily, So we use the threading module to implement multithreaded programming. Generally speaking, there are two modes of using threads, one is to create a function to execute the thread, pass it into the thread object, let it execute, the other is to inherit directly from thread, create a new class, and put the thread execution code into this new class.
Passing functions into the thread object
Copy Code code 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 thread Objects 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 child threads to exit in main thread
For thread in Thread_list:
Thread.Join ()
if __name__ = = "__main__":
Main (3)
The program starts with 3 threads and prints the thread name of each thread, which is easy to do, and it's useful to handle repetitive tasks, as described in the following ways of using inherited threading;
inherited from Threading. Thread class
Copy Code code 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 following articles will describe how to control these threads, including the exit of child threads, the existence of child threads, and the setting of child threads as Daemons (Daemon).