Pause Self, Resume on Event

dsimcha dsimcha at yahoo.com
Wed Jul 16 12:16:47 PDT 2008


I'm trying to implement a low-overhead thread pool library that avoids busy
waiting, and the issue I keep running into is, if a thread is waiting on a job
in the pool queue, how to get the waiting thread to pause and then be resumed
by the worker thread when the job is finished, w/o creating any race hazards.
 Below is a simplified example:

class Task {
    bool isDone = false;
    Thread[] waitingThreads;  //Threads waiting for task to complete.

    //int delegate(), etc., etc.

    void wait() {
        if(isDone) return;
        Thread self = Thread.getThis;
        synchronized(this) {
            waitingThreads ~= self;
            self.pause;
        }
    }

    void resumeWaiting() {  //Called by worker function when done w/ task.
        isDone = true;
        foreach(waiting; waitingThreads) {
            waiting.resume;
        }
    }
}

This probably wouldn't work because, since resumeWaiting is not synchronized,
it could theoretically be called while a thread is in the process of adding
itself to waitingThreads.  In this case, resume would never get called for
this thread.

If I synchronize resumeWaiting, then the thread that called wait() goes to
pause inside a mutex, and nothing can get access to my instance of Task to
resume it.

The third option would be to synchronize only the append to waitingThreads and
not the call to pause(), and to synchronize resumeWaiting().  However, then it
seems theoretically possible that the thread calling wait() would be suspended
by the scheduler before it called pause(), and if resumeWaiting() were then
called before the thread calling wait() got another timeslice, I'd have a
resume-before-pause.  I'm fairly (read:  very) new to concurrent programming.
 Is there a standard solution to problems like this?


More information about the Digitalmars-d-learn mailing list