程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The third notes of 2022 Python winter vacation advanced training

編輯:Python

1. A thread is the smallest unit of program execution , The process is the smallest unit of resources allocated by the operating system

2. Does a process consist of multiple threads , Threads are different execution paths of code in a process

3. Processes are independent of each other , But each small thread in the same process shares the memory space of the program ( Including code snippets , Data sets , Pile etc. ) And some process level resources ( Such as : Open folder and signal ), Threads in one process are not visible to other processes

4. Scheduling and switching : Thread context switching is much faster than process context switching

Create multithreading Example :

import threading # Guide pack
import time
def test(x):
print(x)
time.sleep(2)
# test(1)
# test(2)
# # The first way to create a thread
# t1 = threading.Thread(target=test,args=(1,))
# # Method name # Parameters
# t2 = threading.Thread(target=test,args=(2,))
# # Method name # Parameters
# t1.start()
# t2.start()
# The second way to create a thread Create a class
class MyTheard(threading.Thread):
def __init__(self,n):
super(MyTheard, self).__init__()
self.n = n
def run(self):
print(" Create multithreading as a class ,self.n")
r1 = MyTheard(11) # Create a thread
r2 = MyTheard(22)
r1.start() # Start thread
r2.start()

Multithreading features

1.        t.setDaemon(True) # Setting up the guardian thread : Wait for other threads to finish before ending   Or end with other threads in advance

2.        t1.join() # call join function effect : wait until t1 Start other threads after the thread ends

3.        print(threading.active_count()) # Print the number of active threads

4.        threading.current_thread() View current thread The thread calling the method

Example :

""" Multithreading features """
import threading
import time
def run(x,n):
print(f" Threads {x}")
time.sleep(n)
if __name__=='__main__':
# 1970 How many seconds has it taken to get there
# print(time.time())
start_time = time.time()
res = []
for i in range(10):
if i == 9:
i = 2
t = threading. Thread(target=run,args=(i,i))
t.setDaemon(True) # Setting up the guardian thread : Wait for other threads to finish before ending
# Or end with other threads in advance
t.start()
res.append(t)
print(threading.active_count())
for t in res:
t.join()
# run(1)
# run(2)
print(f"run() The function runs {time.time() - start_time} second ")
# t1 = threading.Thread(target=run,args=(1,))
# t2 = threading.Thread(target=run,args=(2,))
# t1.start()
# t1.join() # call join function effect : wait until t1 Start other threads after the thread ends
# t2.start()
# View active threads
#threading.active_count()
print(threading.active_count()) # Print the number of active threads
# threading.current_thread() View current thread The thread calling the method 

3、 ... and 、 Thread lock

lock = threading.Lock() # Create thread lock : Code in a thread lock can only be executed by one thread at the same time

''' Thread lock '''
import threading
def run():
global x # Modify global variables
lock.acquire() # Apply for program lock
x+=1
lock.release() # Release thread lock
if __name__ == '__main__':
x = 0
res = [] # Create a list of
lock = threading.Lock() # Create thread lock
for i in range(100):
t = threading.Thread(target=run)
t.start()
res.append(t) # Load the thread into the list
for t in res: # Traverse the list
t.join() # Wait for the previous thread to end before calling to start the next thread
print(x)
When thread lock covers thread lock , Use recursive locks RLock
''' Recursive lock '''
# Recursive lock :RLock
import threading
def run1():
global x
lock.acquire() # lock 2
x+= 1
lock.release() # lock 2
return x
def run2():
global y
lock.acquire()
y+= 1
lock.release()
return y
def run3():
lock.acquire() # lock 1
res1 = run1()
res2 = run2()
lock.release() # lock 1
print(res1,res2)
if __name__ == '__main__':
x = 0
y = 0
lock = threading.RLock() # Nested lock in lock Use RLock
for i in range(3):
t = threading.Thread(target=run3)
t.start()
while threading.active_count() != 1:
print(f' Running {threading.active_count()} Threads ')
print(' Thread end ')
 Get the current time and print
import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

python Time and date :
https://www.runoob.com/python/python-date-time.html

python Learning video
https://space.bilibili.com/196858266/video


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved