【发布时间】:2017-11-09 08:40:27
【问题描述】:
假设我有一个名为tasks 的表。每个任务都有一个status。我将其中一项处于To Manage 状态的任务置于In Management 状态,然后运行为其创建任务的过程(可能需要几秒钟才能完成)。
在执行结束时,任务可能会返回To Manage 或Completed 状态,这取决于是否必须再次运行该过程。
现在假设有多个进程同时运行此活动,以便一起完成或以其他方式处理多个不同的任务。
我想确保两个进程不会同时管理同一个任务。为此,上述活动应在事务中执行:
$db->beginTransaction(); /* transaction A */
/* Reads one task from the database (SELECT query with LIMIT 1) which is in the `To Manage` status and returns it */
$task = $tasks->getNextTask(); /* operation 1 */
/* Changes the status into the `In Management` status (UPDATE query) */
$task->changeStatusToManage(); /* operation 2 */
$db->commit();
$task->execute(); /* operation 3 */
我使用的是 MySql 数据库,表是 InnoDB,具有 READ COMMITTED 隔离级别:https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html
我们说To Manage 状态下只有一个任务。如果同时执行两个进程(P1 和 P2)并且 transaction A 不存在,则可能会发生以下情况:
Instant 1: (operation 1) P1 reads the task id 100 in `To Manage` status
Instant 2: (operation 1) P2 reads the task id 100 in `To Manage` status
Instant 3: (operation 2) P1 puts the task id 100 in the `In Management` status
Instant 4: (operation 2) P2 puts the task id 100 in the `In Management` status
Instant 5: (operation 3) P1 performs the task id 100
Instant 6: (operation 3) P2 performs the task id 100
但是,操作 1-2-3 实际上是在事务中执行的,这种情况应该是不可能的。
- 您能否确认确实如此?
- 是否需要在执行操作 1 之前执行显式
LOCK以读取任务表,并在操作 2 完成后释放它? - 我还应该做些什么来防止意外结果?
DB 结构比上面描述的要复杂得多。当我更改任务状态时,我也会在另一个表上写入日志。这是由代码(模型类)本身完成的。我有任务表,task_status 表,任务上有一个外键,还有一个 task_status_change(即日志表)。每个 txn 执行 1 次读取(获取任务),2 次写入(更改状态和写入日志)。所以我需要执行类似的操作(伪代码):
BEGIN;
$id = SELECT task_id FROM task WHERE task_status_id = 1 LIMIT 1;
UPDATE task SET task_status_id = 2 WHERE task_id = $id;
INSERT INTO task_status_change SET task_id = $id, task_status_id = 2;
COMMIT;
如上所述,我使用的是 READ COMMITED 隔离级别。我尝试同时启动两个进程,在同一个任务池上一起运行。
第一个进程选择的任务 ID(ID 和时间戳):
55 1496925510
274 1496925512
384 1496925512
589 1496925513
648 1496925513
1088 1496925513
1990 1496925513
第二个进程选择的任务 ID(ID 和时间戳):
55 1496925510
274 1496925512
589 1496925512
648 1496925513
810 1496925513
1088 1496925513
2049 1496925514
谢谢
【问题讨论】:
-
您是说处理过程需要很长时间才能简单地锁定一行直到完成(几秒钟)?
-
阅读@Rick James 的回答:我必须使用 FOR UPDATE 锁。
标签: mysql transactions innodb commit database-concurrency