测试 MySQL 锁定是否正常工作
我有一个名为 events
的表,其中包含游戏中的事件,例如建筑、研究等。每个事件都有一个 时间戳
指示其完成时间。引擎:innoDB
每次页面加载时,程序都会在 events
表中快速搜索 timestamp
过去的行(即事件已完成)。它选择这些行,然后删除它们,以便任何其他运行都看不到和处理相同的事件。
我担心的是,如果发生两个 pagelod,以便在一个或另一个有机会删除读取的行之前,两个 pagelod 都读取相同的行,以及如果在选择和删除之间发生事件会发生什么。
我认为应该解决它的是:
SET @now=NOW();
SELECT * FROM `events` WHERE `timestamp` < @now FOR UPDATE
DELETE FROM `events` WHERE `timestamp` < @now
但我在测试它时遇到了一些麻烦。我将如何测试这是否按预期工作?
I have a table named events
, which contains in-game events such as construction of buildings, research, etc.. Each event has a timestamp
indicating when it completes. Engine: innoDB
Every pageload, the program runs a quick search of the events
table for rows where timestamp
is in the past (ie. the event has been completed). It selects these rows then deletes them so any other runs don't see and process the same events.
What I'm worried about is what would happen if two pagelods happened so that both of them read the same rows before one or the other has a chance to delete the read rows, and what if an event happens right between selecting and deleting.
What I'm thinking should fix it is:
SET @now=NOW();
SELECT * FROM `events` WHERE `timestamp` < @now FOR UPDATE
DELETE FROM `events` WHERE `timestamp` < @now
But I'm having some trouble testing it. How would I go about testing whether or not this is working as it should?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要在这里回答我自己的问题:p
在
select
和delete
之间使用sleep()
,并同时进行两个调用。最终代码:
结果:
这与睡眠有关。如果没有睡眠,两者都会在 0.002 秒内结束。
Going to answer my own question here :p
Use
sleep()
between theselect
anddelete
, and have two calls at the same time.Final code:
Results:
That's with the sleep. Without the sleep both end in under 0.002 seconds.