SoFunction
Updated on 2025-03-02

python multithreading can be solved like this

Multi-threaded

Multithreading is similar to executing multiple different programs at the same time. Multithreading has the following advantages:

Using threads can put tasks in programs that occupy a long time in the background to process.
The user interface can be more attractive. For example, if the user clicks a button to trigger the processing of certain events, a progress bar can pop up to display the progress of the processing.
The program may run faster.
Threading is more useful in some waiting tasks implementations such as user input, file reading and writing, and network sending and receiving data. In this case, we can free up some precious resources such as memory usage, etc.

Create thread

There must be a main thread in a process.

Two ways to create threads
inheritThreadkind,And rewrite itrun()method
import threading
import time
cLass MyThread():
	def__ init__ (seLf, n):
		super (MyThread, seLf).__ init__()
		 = n
	def run(self):
		print('Create multithreading in class',)
		(3)
r1 = MyThread(1)
r2 = MyThread(2)
()
()
CallthreadingLibraryThreadkind
import threading
import time
def test(x):
    print(x)
    (2)
if __name__=='__main__':
    t1 = (target=test, args=(1,))  
    t2 = (target=test, args=(2,))
    ()
    ()

Daemon threadThe characteristic of this type of thread is that when the main thread and all non-daemon threads in the program end, the unexecuted daemon thread will also die (in a dead state) and the program will end.

#Daemon threadimport threading
import time
def run(n):
    print('task',n)
    (1)
    print('3s')
    (1)
    print('2s')
    (1)
    print('1s')
if __name__ == '__main__': #Main thread    t=(target=run,args=('t1',))
    (True) #Set the child thread as a daemon thread and guard the main thread.  The main thread ends and the child thread ends immediately.  Must be set before the start() method call    ()
    print('end')

Thread lock

1.Mutex lock

#mutex lockimport threading
def run():
    global x
    () #Apply for lock    x+=1 
    () #Release the lockif __name__=='__main__':
    x=0
    res=[]
    lock=() #Instantiate thread lock    for i in range(100): #100 threads        t=(target=run) 
        ()
        (t)
    for t in res:
        ()    
    print(x) 
2.Recursive lock

import threading
def func(lock):
    global gl_num
    ()
    gl_num += 1
    (1)
    print(gl_num)
    ()
if __name__ == '__main__':
    gl_num = 0
    lock = ()
    for i in range(10):
       t = (target=func,args=(lock,))
       ()

Practice:

import threading
import time  #Import time module
#Thread 1: Output the current year, month, day, hour, minute, and secondclass myThread1():
    def run(self):
        while (True):
            print(((())))#Output real-time time            (1)
#Thread 2: name printout 4 times every 2 secondsclass myThread2():#inherit    def __init__(self,name):#Inheriting the parent class method to implement inheritance        super(myThread2, self).__init__()#super method calls the parent class        =name #Instantiate object properties    def run(self):#Rewrite the run method in the Thread class        for i in range(4):#for loop printing 4 times            print()          
            (2)#Print delay for two seconds onceif __name__ == '__main__':
    #Create thread 1 and thread 2 and pass in parameters    x1 = myThread1()
    x2 = myThread2("Zhang San")
    #Open thread    ()
    ()

Summarize

That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!