Python's Lib provides two ways to use threads in Python. One is a function, a thread object that is wrapped with a class. For two simple examples, please refer to Python's documentation and related information for other knowledge of multithreaded programming such as mutexes, semaphores, critical areas, etc.
1, call the Start_new_thread () function in the thread module to generate a new thread, see Code:
Copy Code code 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
& nbsp; Thread.start_new_thread (Timer, (1,1))
Thread.start_new_thread (timer, (2,3))
If __name__== ' __main__ ':
Test ()
This is the Thread.start_new_thread (Function,args[,kwargs]) function prototype, where the function argument is the thread that you want to call; args is the argument that passes to your thread function, he must be a tuple type , and Kwargs is an optional parameter.
The end of a thread generally relies on the natural end of the thread function, or it can be called thread.exit () in a thread function, and he throws Systemexit exception to exit the thread.
2, inherit threading by calling threading module. Thread class to wrap a threading object. Please look at the code:
Copy Code code 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 thread function here
While True:
print ' Thread Object (%d), time:%s '% (Self.no,time.ctime ())
Time.sleep (Self.interval)
def test ():
Threadone=timer (1,1) #产生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 modules also contain a lot of other things about multithreaded programming, such as locks, timers, get a list of activated threads, and so on, please refer to the Python documentation carefully!