In Python, we mainly use thread and threading module to realize, in which Python's threading module is a wrapper for thread, it can be more convenient to be used, so we use the threading module to realize multi-threaded programming. Generally speaking, there are two modes of using threads, one is to create a function to be executed by the thread, and pass this function into the Thread object for it to execute; the other is to inherit directly from Thread, create a new class, and put the code executed by the thread into this new class.
Pass the function into the 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" %( ().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((target = thread_fun, name = thread_name, args = (20,)))
# Start all the threads
for thread in thread_list:
()
# Wait for all child threads to exit in the main thread
for thread in thread_list:
()
if __name__ == "__main__":
main(3)
The program starts three threads, and prints the thread name of each thread, this is relatively simple, right, to deal with repetitive tasks will be sent to the field, the following describes the use of inheritance threading;
Inherited from class
'''
Created on 2012-9-6
@author: walfred
@module: thread.ThreadTest2
'''
import threading
class MyThread():
def __init__(self):
.__init__(self);
def run(self):
print "I am %s" %
if __name__ == "__main__":
for thread in range(0, 5):
t = MyThread()
()
The next article will describe how to control these threads, including the exit of child threads, whether the child threads are alive or not, and setting the child threads as Daemon.