0

I am currently learning about Game Programming with the book 'Game Engine Architecture' authored by Jason Gregory.

In this book, he showed an example with the reason for using 'Condition Variable'

[Without Condition Variable]

Queue g_queue;
pthread_mutex_t g_mutex; bool
g_ready = false;

void* ProducerThread(void*) 
{
    // keep on producing forever... 
    while (true) 
    {
        pthread_mutex_lock(&g_mutex);
        // fill the queue with data 
        ProduceDataInto(&g_queue);
        g_ready = true; 

        pthread_mutex_unlock(&g_mutex);
        // yield the remainder of my timeslice 
        // to give the consumer a chance to run pthread_yield();
    } 
    return nullptr;  
}

void* ConsumerThread(void*) 
{
    // keep on consuming forever... 
    while (true) 
    {
        // wait for the data to be ready 
        while (true) 
        {
             // read the value into a local, 
             // making sure to lock the mutex 
             
             pthread_mutex_lock(&g_mutex); 
             const bool ready = g_ready; 
             pthread_mutex_unlock(&g_mutex);
             
             if (ready) break;
        } 
        // consume the data 
        pthread_mutex_lock(&g_mutex); 
        ConsumeDataFrom(&g_queue); 
        g_ready = false; 
        pthread_mutex_unlock(&g_mutex);
        // yield the remainder of my timeslice 
        // to give the producer a chance to run pthread_yield();
    } 
    return nullptr; 
}

In this example, he said 'Besides the fact that this example is somewhat contrived, there’s one big problem with it: The consumer thread spins in a tight loop, polling the value of g_ready'

I found that the function 'pthread_mutex_lock(&g_mutex)' is a blocking function that if the calling thread can't acquire the mutex, it falls to asleep.

Then, isn't that the consumer thread is not on the state of 'busy-wait'? I mean, doesn't it spin at all if it does not acquire the mutex?

선상원
  • 13
  • 2
  • At the risk of coming off as self-serving, [you might find this interesting](https://stackoverflow.com/questions/14924469/does-pthread-cond-waitcond-t-mutex-unlock-and-then-lock-the-mutex/14925150#14925150). – WhozCraig Jun 21 '21 at 04:52
  • 1
    All this seems to be a C code. The same code in C++ would use atomics. – 273K Jun 21 '21 at 04:57

1 Answers1

0

Though pthread_mutex_lock is a blocking function, the producer and consumer loop will spin tightly. Because either ProduceDataInto or ConsumeDataFrom executed and returns immediately, the mutex repeats lock/unlock after each calling ProduceDataInto/ProduceDataInto.

So there must be a queue-full Condition Variable to make the producer wait and a queue-empty Condition Variable to make the consumer wait.

exudong
  • 366
  • 3
  • 13