Two ways to program Python threads
- 2020-05-09 18:48:21
- OfStack
If threads are to be used in Python, python's lib provides two ways. One is a function and the other is a thread object wrapped in a class. To give two simple examples, please refer to the documentation of python for other knowledge about multithreaded programming, such as mutual exclusion, semaphores, critical sections, etc.
1. Call the start_new_thread() function in thread module to generate a new thread, please see the code:
### thread_example.py
import time
import thread
def timer(no,interval): # Write their own thread function
while True:
print 'Thread :(%d) Time:%s'%(no,time.ctime())
time.sleep(interval)
def test(): # use thread.start_new_thread() To produce 2 Five new threads
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 parameter is the thread function you are going to call; args is the parameter of the thread function that is passed to you. It must be of type tuple. kwargs is an optional parameter.
The end of thread 1 generally depends on the natural end of thread function; You can also call thread.exit () from the thread function, which throws SystemExit exception to exit the thread.
2. Wrap a thread object by calling the threading module to inherit the threading.Thread class. Look at the code:
import threading
import time
class timer(threading.Thread): # my timer Class inherits from threading.Thread class
def __init__(self,no,interval):
# In my rewrite __init__ Remember to call the base class when calling a method __init__ methods
threading.Thread.__init__(self)
self.no=no
self.interval=interval
def run(self): # rewrite run() Method to put its own thread function code here
while True:
print 'Thread Object (%d), Time:%s'%(self.no,time.ctime())
time.sleep(self.interval)
def test():
threadone=timer(1,1) # produce 2 Thread object
threadtwo=timer(2,3)
threadone.start() # By calling the thread object .start() Method to activate the thread
threadtwo.start()
if __name__=='__main__':
test()
In fact, the modules of thread and threading also contain many other things about multithreaded programming, such as locks, timers, getting a list of active threads, etc., please refer to the documentation of python carefully!