python3 基于原语锁的简单同步

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() 
 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值