Two programming methods for Python threads: python Thread Programming
To use a thread in Python, python lib provides two methods. One is a function type, and the other is a thread object encapsulated by a class. I would like to give two simple examples. For more information about multithreaded programming, such as mutex, semaphore, and critical section, please refer to the python documentation and related materials.
1. Call the start_new_thread () function in the thread module to generate a new thread. Please refer to the Code:
Copy codeThe Code is as follows:
### Thread_example.py
Import time
Import thread
Def timer (no, interval): # self-written thread function
While True:
Print 'thread :( % d) Time: % s' % (no, time. ctime ())
Time. sleep (interval)
Def test (): # Use thread. start_new_thread () to generate two new threads.
Thread. start_new_thread (timer, (1, 1 ))
Thread. start_new_thread (timer, (2, 3 ))
If _ name __= = '_ main __':
Test ()
This is thread. start_new_thread (function, args [, kwargs]) function prototype. The function parameter is the thread function to be called. The args parameter is the parameter that is passed to your thread function, it must be of the tuple type, and kwargs is an optional parameter.
The end of a thread generally ends naturally by the thread function. You can also call thread. exit () in the thread function to throw SystemExit exception to exit the thread.
2. Call the threading module to inherit the threading. Thread class to encapsulate a Thread object. See the Code:
Copy codeThe Code is as follows:
Import threading
Import time
Class timer (threading. Thread): # My timer class inherits from the threading. Thread class.
Def _ init _ (self, no, interval ):
# When I override the _ init _ method, remember to call the _ init _ method of the base class.
Threading. Thread. _ init _ (self)
Self. no = no
Self. interval = interval
Def run (self): # rewrite the run () method and 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 () # generate two thread objects
Threadtwo = timer (2, 3)
Threadone. start () # activate a thread by calling the. start () method of the thread object
Threadtwo. start ()
If _ name __= = '_ main __':
Test ()
In fact, the thread and threading modules also contain many other things about multithreading programming, such as locks, timers, and list of activated threads. Please refer to the python documentation carefully!