鎖:
importthreading,time
defaddnum():
global
num lock.acquire()
#獲取鎖
temp=num
time.sleep(0.01)
#print('ok')
num=temp-1lock.release()
#釋放鎖
#鎖保證執行緒沒有執行完cpu不會執行別的執行緒
num=100lst_thread=
lock=threading.lock() #
例項鎖物件
for i in range(100):
t=threading.thread(target=addnum)
t.start()
for t in lst_thread: #
等到所有執行緒執行完畢,在執行主線程
t.join()
print('
num:
',num)
遞迴鎖:
importtime,threading
class
account:
def__init__
(self,_id,balance):
self.id=_id
self.balance=balance
#每乙個使用者都有自己的乙個鎖,保證資料安全性
self.lock=threading.rlock() #
遞迴鎖def withdraw(self,amount): #
取錢with self.lock:
self.balance-=amount
#相當於
#self.lock.acquire()
#self.balance -= amount
#self.lock.release()
def deposit(self,amount): #
存錢with self.lock:
self.balance+=amount
def drawcash(self,amount): #
在算過利息後提錢
with self.lock:
interest=0.05count=amount+amount*interest
#lock.acquire中巢狀lock.acquire
self.withdraw(count)
def transfer(_from,to,amount): #
不同賬戶之間轉錢
#鎖不能在這,因為如果別的操作在對balance進行操作的時候,資料不安全
_from.withdraw(amount)
to.deposit(amount)
a=account('
001',1000)
b=account('
002',500)
t1=threading.thread(target=transfer(a,b,100))
t1.start()
t2=threading.thread(target=transfer(b,a,150))
t2.start()
t1.join()
t2.join()
(a.balance)
print(b.balance)
Python threading多執行緒
目錄1 2 lock encoding utf 8 import threading import time from queue import queue def thread 1 job print thread 1 start n for i in range 10 time.sleep 0....
Python threading(執行緒模組)
建立和使用方式基本和程序一致。有關執行緒的文字講述,請見 計算機 程序 執行緒 協程 import time from threading import thread,current thread,enumerate,active count def func i1,i2 i i1 i2 time....
簡述python(threading)多執行緒
一.概述 import threading 呼叫 t1 threading.thread target function args join 在子執行緒完成執行之前,這個子執行緒的父執行緒將一直被阻塞。setdaemon true 將執行緒宣告為守護執行緒,必須在start 方法呼叫之前設定,如果不...