Rails 3 事务和竞争条件
我正在创建一个浏览器角色扮演游戏,其中玩家拥有库存和仓库。想象一下,在某个时刻,用户想要将物品从库存移动到仓库。现在安全措施必须严密。
我想这一定是一笔交易。现在,您可以在这里看到竞争条件的可能性。从库存->仓库移动的同时从仓库->库存移动可能意味着项目是重复的。
那么,我该如何处理才能确保不会发生类似的情况?
编辑——该示例的竞争条件
从 inv 移动到仓库是一个函数,其中 inv 中的项目首先添加到仓库,然后从库存中删除。从仓库转移到库存也是同样的想法。
现在,想想两个同时进行的动作。库存移动功能将项目添加到仓库。与此同时,相反的情况开始了。仓库将确切的物品移动到库存中。它将找到要移动的项目,因为它刚刚被移动。库存现在从库存中删除项目。仓库从仓库中删除项目。
结果:物品丢失
i'm creating a browser rpg game where the player has an inventory and a warehouse. Imagine that at some point, a user wants to move an item from the inventory to the warehouse. And now the security has to be tight.
I suppose that this has to be a transaction. Now, you see the possibilities for a race condition here. Move from inv->warehouse at the same time as move from warehouse->inv could mean that an item is duplicated.
So, how can i handle that to make sure nothing like that happens ?
EDIT -- RACE CONDITION FOR THAT EXAMPLE
Moving from inv to warehouse is a function where the item from inv is first added to warehouse and then deleted from the inventory. Moving from warehouse to inv is the same idea.
Now, think of 2 simultaneous moves. An inv moving function adds item to warehouse. At the very same time, the opposite begins. A warehouse moves the exact item to inventory. It will find the item to move, since it was just moved. The inventory now deletes item from inventory. The warehouse deletes item from warehouse.
Result : Item is lost
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我实际上在《Agile Rails》一书中找到了如何防止竞争条件。这是金钱交易的方式:
I actually found how to prevent the race condition in the Agile Rails book. This is how it would be done with a transaction for money :
Spyros,
将其放入交易中可以解决一些问题,但不一定是全部。请参阅此问题:
数据库事务会阻止竞争条件吗?
Spyros,
Putting this in a transaction will solve some problems, but not necessarily all. See this question:
Do database transactions prevent race conditions?