1、简单的银行提款程序:
import threading ,time,random
class Account(threading.Thread):
lock=threading.Lock();
def __init__(self,amount):
threading.Thread.__init__(self)
Account.amount=amount
def 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 0
time.sleep(random.choice(range(5)))
prev = Account.amount
Account.amount -= a
print('{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,random
class Container1():
def __init__(self):
self.contents=0
self.available=False
self.cv=threading.Condition()
def put(self,value):
with self.cv:
if self.available:
self.cv.wait()
self.contents=value
t=threading.current_thread()
print('{0}生产{1}'.format(t.name,self.contents))
self.available=True
self.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=False
self.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()