problem with implementing a simple work queue

Posted by John Deerikio on Stack Overflow See other posts from Stack Overflow or by John Deerikio
Published on 2010-05-08T20:21:06Z Indexed on 2010/05/08 20:28 UTC
Read the original article Hit count: 216

Filed under:
|
|
|
|

Hi all,

I am having troubles with implementing a simple work queue. Doing some analysis, I am facing a subtle problem. The work queue is backed by a regular linked list. The code looks like this (simplified):

0. while (true)  
    1. while (enabled == true)  
        2. acquire lock on the list and get the next action to be executed (blocking operation)  (store it in a local variable)  
        3. execute the action (outside the lock on the list on previous line)
    4. get lock on this work queue  
        5. wait until this work queue has been notified (triggered when setEnabled(true) has been callled)

The setEnabled(e) operation looks like this (simplified):

enabled = e
if (enabled == true)
    acquire lock on this work queue and do notify()

Although this works, there is a condition in which a deadlock occurs. It happens in the following rare situation:

  • while an action is being executed, setEnabled(false) is called
  • just before step (4) is entered, setEnabled(true) is called
  • now step (5) keeps waiting forever, because this work queue has already been notified

How do I solve this? I have been looking at this for some time, but I cannot come up with a solution.

Please note I am fairly new to thread synchronization.

Thanks a lot.

© Stack Overflow or respective owner

Related posts about work

Related posts about queue