本博文源于python基礎炫酷技能,主要講述python的線程的問題。大家學到多線程的時候隻要搞明白兩種東西即可,第一線程通信,另一個叫做線程沖突。本博文就以一種列印數字的方法淺析線程沖突的解決方案!
線程沖突起因
例子:多線程累加資料到5百萬
沒使用多線程之前
實驗效果
實驗代碼
import _thread
import time
num = 0
def add():
global num
for i in range(1000000):
num += 1
print(num)
for i in range(5):
add()
這裡的代碼非常直覺和淺顯,大家應該都能了解
使用多線程出現的沖突
實驗效果
實驗代碼
這裡就調用了python的包,結果發現操作資料出現亂序的效果
import _thread
import time
num = 0
def add():
global num
for i in range(1000000):
num += 1
print(num)
for i in range(5):
_thread.start_new_thread(add,())
while True:
pass
解決方案
第一種:join解決線程沖突
實驗效果
實驗代碼中加上了join函數,join函數就是等待主程式執行完畢後才開始下一個線程的執行,是以可以有序的列印。while true是阻塞程式必備。
import threading
import time
num = 0
class Mythread(threading.Thread):
def run(self):
global num
for i in range(1000000):
num += 1
print(num)
for i in range(5):
t = Mythread()
t.start()
t.join()
while True:
pass
第二種:用鎖解決
用鎖的時候,一段線程通路時,另一個線程無法通路。是以這樣也會成功的解決,效果圖跟上面一樣不用多贅述。需要強調的是,整個建立鎖的流程需要大家記憶。
- 建立鎖
- if判斷鎖,進行加鎖
- 解鎖
其中建立鎖:
mutex = threading.Lock()
判斷鎖:
if mutex.acquire(1):
解鎖:
mutex.release()
import threading
import time
# 線程·沖突
# 線程·通信
num = 0
mutex = threading.Lock()
class Mythread(threading.Thread):
def run(self):
global num
if mutex.acquire(1):
for i in range(1000000):
num += 1
mutex.release()
print(num)
mythread = []
for i in range(5):
t = Mythread()
t.start()
mythread.append(t)
for thnum in mythread:
thnum.join()
print("over....")
以上就是python解決線程沖突問題,大家get了嗎?