0

I am trying to wake up a thread queue to process some data, except it's not waking up. Not sure if my approach is flawed. Here is my code:

Main:

struct ThreadOperationStruct _THREADIO;

int main(int argc, char** argv) 
{
    // threads get created here...
}

My waiting thread:

void DecompressLogFile::Wait()
{
    while (!_THREADIO.EndEvent)
    {
        pthread_mutex_lock(&Lock);
        size_t QueueSize = _THREADIO.DecompressLogQueue.size();

        if (!QueueSize)
        {
            // Prevent further thread execution
            fprintf(stdout, "DecompressLogFile() thread sleeping...\n");
            pthread_cond_wait(&_THREADIO.DecompressQueueNotify, &Lock);
        } else {
            fprintf(stdout, "Processing compressed log files. Queue size is now %lu\n", QueueSize);
            /*
             * Async tasks need to go here...
             */
            //BZIP2_DecompressFile();
            _THREADIO.DecompressLogQueue.pop();
        }
    }

    fprintf(stdout, "Wait() end\n");
}

Another class on another thread:

    _THREADIO.DecompressLogQueue.push(NewLog);
    pthread_cond_signal(&_THREADIO.DecompressQueueNotify);

The struct looks like this:

struct ThreadOperationStruct
{
    std::queue<std::string> DecompressLogQueue;
    std::queue<std::string> ProcessLogQueue;

    void NotifyDecompressThread()
    {
        fprintf(stdout, "notifying..\n");
        pthread_cond_signal(&this->DecompressQueueNotify);
    }

    pthread_cond_t DecompressQueueNotify;
    pthread_cond_t ProcessQueueNotify;
    bool EndEvent = false;
};

extern ThreadOperationStruct _THREADIO;

Now, this question is irrelevant to my question above... but I've only had experience with using C++11 threads on Windows and not on Linux. I've read around that for portability, I should remain with pthread on Linux. But does this hold true with C++14?

Thanks

user0000001
  • 2,092
  • 2
  • 20
  • 48
  • Don't unlock the mutex before your `cond_wait.` It does it as part of its operation. Though admittedly self-serving [**read this**](https://stackoverflow.com/questions/14924469/does-pthread-cond-waitcond-t-mutex-unlock-and-then-lock-the-mutex/14925150#14925150). – WhozCraig Jul 25 '16 at 17:56
  • @WhozCraig Updated OP. Thanks. – user0000001 Jul 25 '16 at 17:58
  • it's still wrong. Now you can double-lock your mutex. Seriously. read the linked doc. And btw, if you stick with the `std::thread` library and its components, it should work correctly on any compliant implementation, be it Linux, Windows, BSD, whatever. There should be no need to fallback to POSIX threads unless you're building on targets that don't have C++11 support. – WhozCraig Jul 25 '16 at 17:59
  • @WhozCraig Thank you! – user0000001 Jul 25 '16 at 18:20

0 Answers0