def
runthread
(target,
*args)
:#傳入乙個函式多執行緒執行
print u"啟動執行緒:"
, target.__name__
t = threading.thread(target = target, args = args)
#t.setdaemon(true) #設定為守護執行緒 當主程序結束後所有子執行緒都會結束
t.start(
)def
fun1()
:#每3秒輸出一次fun1 總共輸出5次
for i in
range(5
):print
"fun1"
time.sleep(3)
deffun2
(count, sleep)
:#每sleep輸出一次fun2 總共輸出count次
for i in
range
(count)
:print
"fun2"
time.sleep(sleep)
runthread(fun1)
#建立乙個執行緒執行fun1函式
runthread(fun2,5,
1)#建立乙個執行緒執行fun2函式並給fun2函式傳參5和1
print
"end!"
'''輸出
啟動執行緒: fun1
fun1啟動執行緒:
fun2
fun2end!
fun2
fun2
fun1
fun2
fun2
fun1
fun1
fun1
'''
使用threading模組建立多執行緒
x =
0def
fun1()
:global x
for i in
range
(1000):
x = x +
1def
fun2()
:global x
for i in
range
(1000):
x = x +
1t = threading.thread(target = fun1)
t.start(
)t = threading.thread(target = fun2)
t.start(
)time.sleep(3)
#3秒足夠讓兩個執行緒執行完畢
print x
#輸出1603 和預計不符
多執行緒修改同乙個全域性變數出現問題
lock = threading.lock(
)x =
0def
fun1()
:global lock, x
for i in
range
(1000):
lock.acquire(
)#加鎖
x = x +
1 lock.release(
)#解鎖
deffun2()
:global lock, x
for i in
range
(1000):
lock.acquire(
) x = x +
1 lock.release(
)t = threading.thread(target = fun1)
t.start(
)t = threading.thread(target = fun2)
t.start(
)time.sleep(3)
#3秒足夠讓兩個執行緒執行完畢
print x
#使用互斥鎖 輸出正確結果2000
使用互斥鎖保證資料正確
lock = threading.lock(
)def
runthread
(target,
*args)
:#傳入乙個函式多執行緒執行
print u"啟動執行緒:"
, target.__name__
t = threading.thread(target = target, args = args)
#t.setdaemon(true) #設定為守護執行緒 當主程序結束後所有子執行緒都會結束
t.start(
)def
fun():
global lock
lock.acquire(
)print
"lock"
time.sleep(2)
lock.release(
)print
"unlock"
runthread(fun)
runthread(fun)
for i in
range(5
):time.sleep(1)
print
""#輸出換行
'''輸出
啟動執行緒: fun
啟動執行緒:lock
funnlocklock
nlock
'''
當執行緒使用acquire嘗試鎖定lock時發現已經被鎖定則進入阻塞狀態 等待lock的解鎖再繼續執行
lock = threading.lock(
)x =
0def
fun1()
:global lock, x
for i in
range
(1000):
with lock:
#執行with下指令自動加鎖執行完畢自動解鎖
x = x +
1def
fun2()
:global lock, x
for i in
range
(1000):
with lock:
x = x +
1t = threading.thread(target = fun1)
t.start(
)t = threading.thread(target = fun2)
t.start(
)time.sleep(3)
#3秒足夠讓兩個執行緒執行完畢
print x
with 更加方便的加鎖解鎖 python執行緒互斥鎖 Python多執行緒與互斥鎖
多執行緒 threading python的thread模組是 較底層的模組,python的threading 模組是對thread做了 些包裝的,可以更加 便的被使 1.使 threading模組 from threading import thread 匯入模組 t thread target ...
Python 多執行緒資源競爭及互斥鎖
demo import threading import time g num 0 def fun add 01 num global g num for i in range num g num 1 print g num def fun add 02 num global g num for i...
python多執行緒程式設計 使用互斥鎖同步執行緒
假設乙個例子 有乙個全域性的計數num,每個執行緒獲取這個全域性的計數,根據num進行一些處理,然後將num加1。很容易寫出這樣的 encoding utf 8 import threading import time class mythread threading.thread defrun s...