I come up with a case in our life , here is a time table about the buying bread case . we suppose to get one bread but finally we get two bread. Because two person don't communicate with each other . they find there is no bread in the fridge and they go to buy one .So here is the problem . how to get one bread when two person is involved in this case .
- time Person A Person B
- 3:00 查看冰箱,没有面包了
- 3:05 离开家去商店
- 3:10 到达商店 查看冰箱,没有面包了
- 3:15 购买面包 离开家去商店
- 3:20 到家,把面包放入冰箱 到达商店
- 3:25 购买面包
- 3:30 到家,把面包放入冰箱
My SOLUTION: In order to get only one bread . we could define a critical-section.
if (nobread){
buy bread
}
only one person could go to buy bread at a time.
and we should use lock fuction to implement.
Lock.acquire()
Lock.release()
So the bread problem can be solved easily!
(the code is as following )
breadlock.acquire() <------enter the critical - section
if (nobread){
buy bread
}
breadlock.release() <-------leave the critical - section