troubleshooting Question

C++ Volatile Read/Write

Avatar of dcdillon
dcdillon asked on
C++
10 Comments1 Solution1043 ViewsLast Modified:
I want to do something along the lines shown below where each thread is executing on its own CPU.

What I expect this code to do is have thread1 set doJob = true (provided that doJob is currently false), thread2 to call job() after thread1 has set doJob = true, and then set doJob = false.  After this, of course thread1 will set doJob = true and the process repeats.

The failure would be that the while loops checking the value of doJob outside the critical section would never end because of stale data.

I believe that the volatile keyword used will prevent the compiler from caching the value of doJob and that my lock, unlock pair will guarantee that the other CPUs cache is invalidated and thus the value loaded appropriately and everything executes as expected.  The penalty here, I believe, is the possibility of spurious wakeups (of either thread), and an extra check on doJob which I am willing to suffer.

Can anyone help me to confirm that my analysis is correct/incorrect?
volatile bool doJob = false;
pthread_spinlock_t lock;

void job()
{
    // do some work
}

void thread1()
{
    while (true)
    {
        while (doJob)
        {
        }

        pthread_spin_lock(&lock);
        if (!doJob)
        {
            doJob = true;
        }
        pthread_spin_unlock(&lock);
}

void thread2()
{
    // keep spinning and checking when you should execute
    // job()
    while (true)
    {
        while (!doJob)
        {
        }

        pthread_spin_lock(&lock);
        if (doJob)
        {
            job();
            doJob = false;
        }
        pthread_spin_unlock(&lock);
    }
}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 10 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 10 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros