MySQL producer consumer with multiple select threads

久未见 提交于 2019-12-08 04:04:27

I have a practical solution for you, one that I have seen implemented in a project at my workplace. Instead of using just 0 and 1 for incomplete and completed, expand your set to include more cases.

Let's call that column status. Here are the different values of that column and the corresponding states of the job.

  1. When status is 0, the job has not been picked up by any worker thread.
  2. When status is 1, the job has been picked up by a worker thread and is under process.
  3. When status is 2, the job has failed. (You should consider the possibility of failure in processing.)
  4. When status is 3, the job has been completed.

Your threads should contain logic such that it only picks up jobs for whom the status is 0 and changes the status to 1. This will disallow other threads to pick up those jobs which are under process. When the job completes, the status is set to 3 and if the job fails, the status is set to 2. Then the thread can move on and look for another job that is still to be completed.

You could also ask the threads to consider picking up jobs of status 2, but you will have to define logic to specify a finite number of retries.

EDIT:

After a long discussion, we stumbled upon the solution together. My above answer is good in a more generalized state when the 'job' is a process that takes some time to complete. But that wasn't the case in the OP's problem.

So the solution that eventually worked was this:

BEGIN 
SELECT * FROM Jobs WHERE JobID = (SELECT * FROM Jobs WHERE completed = 0 LIMIT 1) LOCK IN SHARE MODE;
UPDATE Jobs SET completed = 1 WHERE JobID = (PREVIOUS ID); 
COMMIT;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!