# incrmnt.py import db def increment(): count = db.get_count() new_count = count + 1 db.set_count(new_count) return new_count
# 线程1和线程2在不同的进程中同时执行
# 为了展示的目的,在这里并排放置
# 在垂直方向分开它们,以说明在每个时间点上执行什么代码
# Thread 1(线程1) # Thread 2(线程2)
def increment():
def increment():
# get_count returns 0
count = db.get_count()
# get_count returns 0 again
count = db.get_count()
new_count = count + 1
# set_count called with 1
db.set_count(new_count)
new_count = count + 1
# set_count called with 1 again
db.set_count(new_count)
# Thread 1 # Thread 2
def increment():
# get_count returns 0
count = db.get_count()
def increment():
# get_count returns 0 again
count = db.get_count()
# set_count called with 1
new_count = count + 1
db.set_count(new_count)
# set_count called with 1 again
new_count = count + 1
db.set_count(new_count)
# test_incrmnt.py
import unittest
import before_after
import db
import incrmnt
class TestIncrmnt(unittest.TestCase):
def setUp(self):
db.reset_db()
def test_increment_race(self):
# after a call to get_count, call increment
with before_after.after('incrmnt.db.get_count', incrmnt.increment):
# start off the race with a call to increment
incrmnt.increment()
count = db.get_count()
self.assertEqual(count, 2)
# incrmnt.py
def locking_increment():
with db.get_lock():
return increment()
# test_incrmnt.py
def test_locking_increment_race(self):
def erroring_locking_increment():
# Trying to get a lock when the other thread has it will cause a
# CouldNotLock exception - catch it here or the test will fail
with self.assertRaises(db.CouldNotLock):
incrmnt.locking_increment()
with before_after.after('incrmnt.db.get_count', erroring_locking_increment):
incrmnt.locking_increment()
count = db.get_count()
self.assertEqual(count, 1)
# incrmnt.py
def retrying_locking_increment():
@retry(tries=5, errors=db.CouldNotLock)
def _increment():
return locking_increment()
return _increment()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有