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

I have a task_id table that has two columns:

`tid`:task id,
`state`:0:unfinished,1:processing,2:finished

      

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?

+3


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.



+3


source


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.

+2


source







All Articles