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

Multithreading in python (the simplest version in History)

編輯:Python

brief introduction :

Multithreading is simply understood as : One CPU, That is, single core , Cut time into pieces ,CPU Take turns to deal with one thing , The next thing will be dealt with in the specified time .

primary coverage :

1.python Display the properties and methods of the current thread information in

# coding:utf-8
# Import threading package 
import threading
if __name__ == "__main__":
print(" Number of currently active threads ", threading.active_count())
print(" Display the specific information of all current threads ", threading.enumerate())
print(" The information of the current thread is displayed ", threading.current_thread())

design sketch :

2. Add a thread

# coding:utf-8
import threading
import time
def job1():
# Let this thread execute for a few more seconds 
time.sleep(5)
print("the number of T1 is %s" % threading.current_thread())
if __name__ == "__main__":
# Create a new thread 
new_thread = threading.Thread(target=job1, name="T1")
# Start a new thread 
new_thread.start()
print(" The current number of threads is ", threading.active_count())
print(" Details of all threads ", threading.enumerate())
print(" Current thread details ", threading.current_thread())

design sketch :

3. In thread join function

(1) As expected , After executing thread 1, Then the output All done…
“ The ideal is full , The reality is not like this ”

# coding:utf-8
import threading
import time
def job1():
print("T1 start")
for i in range(5):
time.sleep(1)
print(i)
print("T1 finish")
def main():
# Create a new thread 
new_thread = threading.Thread(target=job1, name="T1")
# Start a new thread 
new_thread.start()
print("All done...")
if __name__ == "__main__":
main()

design sketch :

(2) In order to meet our expectations , We use join function , take T1 Thread blocking .join Function to block ? Which thread is used join function , When this thread is executing , The thread program after him cannot execute , After all the blocked threads are executed , Can perform !

# coding:utf-8
import threading
import time
def job1():
print("T1 start")
for i in range(5):
time.sleep(1)
print(i)
print("T1 finish")
def main():
# Create a new thread 
new_thread = threading.Thread(target=job1, name="T1")
# Start a new thread 
new_thread.start()
# Block this T1 Threads 
new_thread.join()
print("All done...")
if __name__ == "__main__":
main()

design sketch :

4. Use Queue Store the results of the thread

Thread execution result , Unable to get return Go back , Use Queue Storage .

# coding:utf-8
import threading
from queue import Queue
""" Queue Use """
def job(l, q):
for i in range(len(l)):
l[i] = l[i] ** 2
q.put(l)
def multithreading():
# Create a queue 
q = Queue()
# The thread list 
threads = []
# 2 d list 
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [6, 6, 6]]
for i in range(4):
t = threading.Thread(target=job, args=(data[i], q))
t.start()
threads.append(t)
# Block all threads 
for thread in threads:
thread.join()
results = []
# Put each element in the new queue into the result list one by one 
for _ in range(4):
results.append(q.get())
print(results)
if __name__ == "__main__":
multithreading()

design sketch :

5. Thread lock lock

When multiple threads are started at the same time , Each thread will preempt computing resources , Can cause procedural confusion .
Take a chestnut :
When we select class hours in the course selection system , At present, there are still 2 Places , The three of us went to choose a course .
The order of course selection is stu1 stu2 stu3, The course selection process of the three students should be printed in turn , But the reality is :

# coding:utf-8
import threading
import time
def stu1():
print("stu1 Start choosing courses ")
global course
if course > 0:
course -= 1
time.sleep(2)
print("stu1 Successful course selection , Now the remaining places in basketball class are %d" % course)
else:
time.sleep(2)
print("stu1 Course selection failed , The quota of basketball class is 0, Please choose another course ")
def stu2():
print("stu2 Start choosing courses ")
global course
if course > 0:
course -= 1
time.sleep(2)
print("stu2 Successful course selection , Now the remaining places in basketball class are %d" % course)
else:
time.sleep(2)
print("stu2 Course selection failed , The quota of basketball class is 0, Please choose another course ")
def stu3():
print("stu3 Start choosing courses ")
global course
if course > 0:
course -= 1
time.sleep(2)
print("stu3 Successful course selection ")
print(" The remaining places in basketball class are %d" %course)
else:
time.sleep(2)
print("stu3 Course selection failed , The quota of basketball class is 0, Please choose another course ")
if __name__ == "__main__":
# Basketball class quota 
course = 2
T1 = threading.Thread(target=stu1, name="T1")
T2 = threading.Thread(target=stu2, name="T2")
T3 = threading.Thread(target=stu3, name="T3")
T1.start()
T2.start()
T3.start()

design sketch :

To solve this situation , We use lock Thread synchronization lock , When threads execute concurrently , Ensure the atomicity of each thread execution . Effectively prevent the sharing of unified data , The chaos of concurrent thread execution . The improved code is as follows :

# coding:utf-8
import threading
import time
def stu1():
global lock
lock.acquire()
print("stu1 Start choosing courses ")
global course
if course > 0:
course -= 1
time.sleep(2)
print("stu1 Successful course selection , Now the remaining places in basketball class are %d" % course)
else:
time.sleep(2)
print("stu1 Course selection failed , The quota of basketball class is 0, Please choose another course ")
lock.release()
def stu2():
global lock
lock.acquire()
print("stu2 Start choosing courses ")
global course
if course > 0:
course -= 1
print("stu2 Successful course selection , Now the remaining places in basketball class are %d" % course)
else:
time.sleep(1)
print("stu2 Course selection failed , The quota of basketball class is 0, Please choose another course ")
lock.release()
def stu3():
global lock
lock.acquire()
print("stu3 Start choosing courses ")
global course
if course > 0:
course -= 1
time.sleep(1)
print("stu3 Successful course selection , Now the remaining places in basketball class are %d" % course)
else:
time.sleep(1)
print("stu3 Course selection failed , The quota of basketball class is 0, Please choose another course ")
lock.release()
if __name__ == "__main__":
# Basketball class quota 
course = 2
# Create a synchronization lock 
lock = threading.Lock()
T1 = threading.Thread(target=stu1, name="T1")
T2 = threading.Thread(target=stu2, name="T2")
T3 = threading.Thread(target=stu3, name="T3")
T1.start()
T2.start()
T3.start()

design sketch :

appendix : Reference from : Don't worry about it python; If it's useful , Remember the praise. + Collection + Focus on !


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