Python threading multithreaded programming example
- 2020-04-02 14:03:44
- OfStack
There are two ways to implement multithreading in Python:
Function, thread class
1. The function
Call the start_new_thread() function in the thread module to create a thread, telling the thread what to do in the form of a thread function
# -*- coding: utf-8 -*-
import thread
def f(name):
# Define a thread function
print "this is " + name
if __name__ == '__main__':
thread.start_new_thread(f, ("thread1",))
# with start_new_thread() Calls thread functions and other parameters
while 1:
pass
However, this method has not found any other auxiliary methods for the moment, even the main thread has to wait with the method of while 1.
2. The thread class
Call the threading module and create a subclass of threading.thread to get the custom threading class.
# -*- coding: utf-8 -*-
import threading
class Th(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
# Call the superclass constructor
def run(self):
# rewrite run() Function from which the thread executes by default
print "This is " + self.t_name
if __name__ == '__main__':
thread1 = Th("Thread_1")
thread1.start()
#start() Function starts the thread and executes automatically run() function
Inheritable function of threading.Thread class:
GetName () gets the thread object name
SetName () sets the name of the thread object
Join () waits for the calling thread to end before running the subsequent command
SetDaemon (bool) blocking mode, True: the parent does not wait for the child to finish, False waits, False by default
IsDaemon () determines whether the child thread ends with the parent thread, which is the value set by setDaemon()
IsAlive () determines whether the thread is running
The instance
import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)
def run(self):
print "This is thread " + self.getName()
for i in range(5):
time.sleep(1)
print str(i)
print self.getName() + "is over"
Join () blocks the wait
if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.start()
#thread1.join()
print "main thread is over"
Without thread1.join(), the following results are obtained:
This is thread T1
main thread is over
0
1
2
T1 is over
The statement is executed without waiting for thread1 to complete.
Add thread1.join() to get the following result:
This is thread T1
0
1
2
T1 is over
main thread is over
The block waits for the end of thread1 to execute the following statement
Main thread waiting
if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.setDaemon(True)
# Set this amount before the thread executes
thread1.start()
print "main thread is over"
Error: Exception in thread T1 (most likely raised during interpreter shutdown):
That is, the main thread ends without waiting for the child thread.
Multiple child threads
if __name__ == '__main__':
for i in range(3):
t = Th(str(i))
t.start()
print "main thread is over"
The t here can handle multiple threads at the same time, that is, t is the handle of the thread, and the reassertion does not affect the thread.
The strange thing here is that when you run t.un (), you don't execute another thread. I don't know, but let's say start(). For the moment, start() is non-blocking and parallel, while run is blocked.
Thread lock
Threading provides a thread lock for thread synchronization.
import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)
def run(self):
threadLock.acquire()
# Get the lock and run again
print "This is thread " + self.getName()
for i in range(3):
time.sleep(1)
print str(i)
print self.getName() + " is over"
threadLock.release()
# Release the lock
if __name__ == '__main__':
threadLock = threading.Lock()
# Set global lock
thread1 = Th('Thread_1')
thread2 = Th('Thread_2')
thread1.start()
thread2.start()
Results:
This is thread Thread_1
0
1
2
Thread_1 is over
This is thread Thread_2
0
1
2
Thread_2 is over