Multithreading (I)
- Create multithreading
- Multithreading feature
- Wire program lock
Learning video link: python multithreading
1. Create multithreading
p66
Multithreading is similar to executing multiple different programs at the same time
Thread, also known as lightweight process, is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operation unit in the process. One thread can create and revoke another thread, and multiple threads in the same process can execute concurrently
- Create in normal way
- Create as a class
#Create in normal way ''' import threading import time def test(x): print('Create multithreading in normal way',x) time.sleep(2) if __name__=='__main__': t1 = threading.Thread(target=test, args=(1,)) # target is the name of the function to be executed (not the function), args is the parameter corresponding to the function and exists in the form of tuple t2 = threading.Thread(target=test, args=(2,)) t1.start() t2.start() ''' #Create as a class import threading import time ''' super(Net, self).__init__() Python Medium super(Net, self).__init__()It means finding it first Net Parent class of (for example, class) NNet), Then put the class Net Object of self Convert to class NNet Object and then "converted" class NNet Object calls its own init Function, In fact, the simple understanding is that the child class takes the parent class's__init__()Put it in your own__init__()In this way, the child class has the parent class__init__()Those things. ''' class mythread(threading.Thread): #Inheriting the parent class threading Thread def __init__(self,n): super(mythread, self).__init__() self.n=n def run(self): #The refactoring run function must write print('Create multithreading as a class',self.n) time.sleep(2) if __name__=='__main__': t1=mythread(1) t2=mythread(2) t1.start() t2.start()
Print as follows:
Create multithreading as a class 1 Create multithreading as a class 2
2. Multithreading
p67
View current thread: threading current_ thread()
View active threads: threading active_ count()
Time module is an important function related to timestamp and time
time.time() generates the current timestamp in the form of a floating-point number of 10 bit integers.
time.strftime() generates a time formatted string based on the time tuple.
time.strptime() generates a time tuple based on the time format string. time.strptime()time.strftime() is interoperable.
time.localtime() generates a time tuple of the current time zone based on the timestamp.
- Knowledge point 1:
When a process is started, a main thread will be generated by default, because the thread is the smallest unit of the program execution flow. When multi threading is set, the main thread will create multiple sub threads. In python, by default (actually setDaemon(False)), the main thread exits after executing its own task, and the sub thread will continue to execute its own task, Until your task is over. - Knowledge point 2:
When we use the setDaemon(True) method to set the child thread as the guardian thread, once the main thread ends execution, all threads will be terminated. The possible situation is that the child thread's tasks will be forced to stop before the full execution is completed. - Knowledge point 3:
At this time, the role of join is highlighted. The work completed by join is thread synchronization, that is, after the main thread task ends, it enters the blocking state and waits for the execution of other sub threads to end, and the main thread terminates
Daemon thread:
The main thread ends and the child thread ends immediately. Must be set before the start() method call
#Daemon thread import threading import time def run(n): print('task',n) time.sleep(1) print('3s') time.sleep(1) print('2s') time.sleep(1) print('1s') if __name__ == '__main__': #Main thread t=threading.Thread(target=run,args=('t1',)) t.setDaemon(True) #Set the child thread as the guardian thread and guard the main thread. The main thread ends and the child thread ends immediately. Must be set before the start() method call t.start() print('end')
Print results (without daemon thread)
task t1 end 3s 2s 1s
Add daemon thread
task t1 end
Thread synchronization join
The main thread waits for all the child threads to end before the main thread itself ends
import threading import time #The job of join is thread synchronization, that is, after the main thread completes its task, it enters the blocking state and waits for the execution of other sub threads, and then the main thread terminates def run(n): print('task',n) time.sleep(1) print('5s') time.sleep(1) print('3s') time.sleep(1) print('1s') if __name__ == '__main__': t=threading.Thread(target=run,args=('t1',)) # t.setDaemon(True) #Setting a child thread as a daemon thread must be set before start() t.start() t.join() #Set the main thread to wait for the child thread to end The main thread waits for all the child threads to end before the main thread itself ends print('end')
Print results (without join)
taskend t1 5s 3s 1s
Add join
task t1 5s 3s 1s end
3. Thread lock (mutex lock and recursive lock)
p68,p69
The following is a code example: description (100 threads will operate x at the same time. If the fifth and sixth threads operate at the same time, they will be disordered. After locking, one thread will operate x every time)
#Wire program lock ''' #mutex import threading def run(): global x lock.acquire() #Apply for lock x+=1 #For each thread, x will add 1 The last is 100 lock.release() #Release lock if __name__=='__main__': x=0 res=[] lock=threading.Lock() #Instantiate thread lock for i in range(100): #100 threads t=threading.Thread(target=run) #t is the thread t.start() res.append(t) for t in res: t.join() #Set the main thread to wait for the child thread to end The main thread waits for all the child threads to end before the main thread itself ends print(x) #100 ''' #Recursive lock RLcok classes as like as two peas of Lock class, but it supports nesting. When RLock locks are not released, they will use the class. #There are two lock (nested) parts of the code when RuN3 - > Run1 import threading def run1(): lock.acquire() global x x+=1 lock.release() def run2(): lock.acquire() global y y+=1 lock.release() def run3(): lock.acquire() r1=run1() r2=run2() lock.release() if __name__=='__main__': x=0 y=0 lock=threading.RLock
Job:
''' In one thread, the current year, month, day, hour, minute and second are output circularly every second; At the same time, in another thread, the name of Zhang San is printed out 4 times every 2 seconds. Note: both need to use classes and inheritance to implement functions ''' import threading import time class mythread1(threading.Thread): #Inheriting the parent class threading Thread def __init__(self,): super(mythread1, self).__init__() def run(self): #The refactoring run function must write while True: time.sleep(1) #Pause for 1 second print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) #Print time class mythread2(threading.Thread): #Inheriting the parent class threading Thread def __init__(self,name): super(mythread2, self).__init__() self.name=name def run(self): #The refactoring run function must write i=0 while i<4: time.sleep(2) print(self.name) i+=1 if __name__=='__main__': t1=mythread1() t2=mythread2('Zhang San') t1.start() t2.start()
Print results: (partial)
2022-01-08 00:43:32 Zhang San 2022-01-08 00:43:33 2022-01-08 00:43:34 Zhang San 2022-01-08 00:43:35 2022-01-08 00:43:36 Zhang San 2022-01-08 00:43:37 2022-01-08 00:43:38 Zhang San 2022-01-08 00:43:39 2022-01-08 00:43:40 2022-01-08 00:43:41 2022-01-08 00:43:42