Rails 3 事务和竞争条件

发布于 2024-10-29 02:12:04 字数 404 浏览 2 评论 0原文

我正在创建一个浏览器角色扮演游戏,其中玩家拥有库存和仓库。想象一下,在某个时刻,用户想要将物品从库存移动到仓库。现在安全措施必须严密。

我想这一定是一笔交易。现在,您可以在这里看到竞争条件的可能性。从库存->仓库移动的同时从仓库->库存移动可能意味着项目是重复的。

那么,我该如何处理才能确保不会发生类似的情况?

编辑——该示例的竞争条件

从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无悔心 2024-11-05 02:12:04

我实际上在《Agile Rails》一书中找到了如何防止竞争条件。这是金钱交易的方式:

Account.transaction do
  account1.deposit(100)
  account2.withdraw(100)
end

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 :

Account.transaction do
  account1.deposit(100)
  account2.withdraw(100)
end
赠我空喜 2024-11-05 02:12:04

Spyros,

将其放入交易中可以解决一些问题,但不一定是全部。请参阅此问题:

数据库事务会阻止竞争条件吗?

Spyros,

Putting this in a transaction will solve some problems, but not necessarily all. See this question:

Do database transactions prevent race conditions?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文