How to avoid race condition if multiple clients choose in MySQL?

I have a task_id table that has two columns:

`tid`:task id,


Easy if I only use one client (Perl script): pick one unfinished

task id, update it to processing

, process it and update to finished

in a loop.

But I am planning on using multiple clients to accomplish this task. There is a possibility that two clients are taking the entry at the same time, how to avoid it?


source to share

2 answers

If your mysql table engine is INNODB, it will lock that particular row when updating the table record so that another query doesn't conflict with the previous update.



The update has something like:

update task_id set state=1 where tid=? and state=0;


then check if the update actually changed the entry.



All Articles