python3 基於原語鎖的簡單同步__python

來源:互聯網
上載者:User

1、簡單的銀行提款程式:

import threading ,time,randomclass Account(threading.Thread):lock=threading.Lock();def __init__(self,amount):threading.Thread.__init__(self)Account.amount=amountdef run (self):self.withdraw()def withdraw(self):Account.lock.acquire()t=threading.current_thread()a=random.choice(range(50,101))if(Account.amount<a):print('{0}交易失敗,取款前金額為{1},取款金額{2}'.format(t.name,Account.amount,a))Account.lock.release()return 0time.sleep(random.choice(range(5)))prev = Account.amountAccount.amount -= aprint('{0}取款前金額為{1},取款金額{2},取款後金額{3}'.format(t.name,prev,a,Account.amount))Account.lock.release()def test():for i in range(5):Account(200).start()if __name__=='__main__':test()

此程式通過對象鎖實現同步,比較容易產生死結,所以對其進行改進。

import threading,time,randomclass Container1():def __init__(self):self.contents=0self.available=Falseself.cv=threading.Condition()def put(self,value):with self.cv:if self.available:self.cv.wait()self.contents=valuet=threading.current_thread()print('{0}生產{1}'.format(t.name,self.contents))self.available=Trueself.cv.notify()def get(self):with self.cv:if not self.available:self.cv.wait()t=threading.current_thread()print('{0}消費{1}'.format(t.name,self.contents))self.available=Falseself.cv.notify()class Producer(threading.Thread): def __init__(self,container): threading.Thread.__init__(self) self.container=container def run(self): for i in range(1,6): time.sleep(random.choice(range(5))) self.container.put(i)class Consumer(threading.Thread): def __init__(self,container): threading.Thread.__init__(self) self.container=container def run(self): for i in range(1,6): time.sleep(random.choice(range(5))) self.container.get()def test(): print('基本同步和通訊的生產者消費者模型:') container=Container1() Producer(container).start() Consumer(container).start()if __name__=='__main__' : test()  



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.