Python provides two ways to use a thread if it is to be used. One is a function, and one is a thread object wrapped in a class. Take two simple examples to get started, and learn more about multithreaded programming, such as mutexes, semaphores, critical sections, and more, and refer to Python's documentation and related materials.
1. Call the Start_new_thread () function in the thread module to generate a new thread, see the code:
Copy CodeThe code is as follows:
# # thread_example.py
Import time
Import Thread
def timer (no,interval): #自己写的线程函数
While True:
print ' Thread:(%d) time:%s '% (No,time.ctime ())
Time.sleep (interval)
def test (): #使用thread. Start_new_thread () to generate 2 new threads
Thread.start_new_thread (timer, ())
Thread.start_new_thread (timer, (2,3))
If __name__== ' __main__ ':
Test ()
This is the prototype of the Thread.start_new_thread (Function,args[,kwargs]) function, where the function parameter is the thread that you are going to call, and args is the argument to the thread function passed to you, he must be a tuple type , while Kwargs is an optional parameter.
The end of a thread is generally dependent on the natural end of the thread function, or thread.exit () can be called in an inline function, and he throws Systemexit exception to exit the thread.
2, inherit threading by calling threading module. The thread class wraps a threaded object. Please look at the code:
Copy CodeThe code is as follows:
Import threading
Import time
Class Timer (threading. Thread): #我的timer类继承自threading. Thread class
def __init__ (Self,no,interval):
#在我重写__init__方法的时候要记得调用基类的__init__方法
Threading. Thread.__init__ (self)
Self.no=no
Self.interval=interval
def run (self): #重写run () method, put the code of your own thread function here
While True:
print ' Thread Object (%d), time:%s '% (Self.no,time.ctime ())
Time.sleep (Self.interval)
def test ():
Threadone=timer (#产生2个线程对象)
Threadtwo=timer (2,3)
Threadone.start () #通过调用线程对象的. Start () method to activate the thread
Threadtwo.start ()
If __name__== ' __main__ ':
Test ()
In fact, the thread and threading module also contains a lot of other things about multithreaded programming, such as locks, timers, get activation thread list, etc., please refer to Python's documentation carefully!