1

I'm trying to simulate the Dining Philosophers problem but I'm having trouble visualising it. When the thread moves from Waiting() to Eating() to Thinking() it changes a variable called state to represent this. However in my main thread it never sees the state variable change. It calls a return function for state when drawing to change the colour of the philosopher.

Any help with this?

Here is some code: State Change

void Philosopher::Eat()
{
    state_ = EATING;
    Sleep(500);
}

Return function

Philosopher::_state Philosopher::ReturnState()
{
    return state_;
}

Call of return function

Philosopher::_state current_state_;
    current_state_ = philosopher_[i].ReturnState();

    switch (current_state_)
    {
        case Philosopher::PICKING:
        {
            glColor3f(1, 0, 0);
            break;
        }

        case Philosopher::EATING:
        {
            glColor3f(0, 1, 0);
            break;
        }

        case Philosopher::THINKING:
        {
            glColor3f(0, 0, 1);
            break;
        }
    }
Alex L
  • 115
  • 11
  • Possibly because the variable you're observing isn't the same one as the one you're modifying. – molbdnilo May 13 '15 at 10:09
  • 1
    [SSCCE](http://sscce.org/) please. – Blacktempel May 13 '15 at 10:37
  • I'm not sure what multithreading standard you're using (C++11? POSIX pthreads?) but most of them prohibit accessing an object in one thread while it is being, or could be, modified in another thread. Presumably the standard you are using provides tools to synchronize access to shared state -- mutexes, atomics, whatever -- use them. – David Schwartz May 13 '15 at 11:39

2 Answers2

1

Without synchronization, attempts to access one variable from multiple threads is Undefined Behavior. Add a mutex.

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

As this is the only question I could find:

Any help with this?

And this question is now 6 months old, I figured I would just show how to do it. Actually here are four ways to do it (in C++):

Dining Philosophers Rebooted

The easy answer is to create an array of std::mutex which represents the fork between each philosopher and lock them (for eating) using std::lock, something like this:

std::unique_lock<std::mutex> left (mutexes[i], std::defer_lock);
std::unique_lock<std::mutex> right(mutexes[j], std::defer_lock);
std::lock(left, right);

If you do this, and you find that your code spends any significant amount of time spinning, write a bug report to your std::lib vendor and point them at this paper. They will recognize it.

Or if you prefer, just copy one of the four ::lock implementations out of the paper (whichever one works best for you) and use it.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577