condition_variable :: wait_for method does not return - even after the timeout

advertisements

I come from C# coding experience; I am beginning to learn C++ and make use of boost libraries for threading. I wrote the following class - trying to execute a member function as a thread. Writing the following simple code, i would expect the while loop inside the thread function to execute every second.

#include <boost/chrono/chrono.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>

using namespace boost;

class MyClassWithThread : public boost::enable_shared_from_this<MyClassWithThread>
{
    mutex                           muThreadControl;
    condition_variable              cvThreadControl;
    bool                            threadToBeStopped = false; 

    void ThreadFunction()
    {
        std::cout << "Beginning the Thread" << std::endl;

        while(true)
        {
            bool endIOThread = false;
            std::cout << "\nChecking if Thread to be stopped: ";
            {
                boost::mutex::scoped_lock lock(muThreadControl);
                endIOThread = cvThreadControl.wait_for(lock,
                    boost::chrono::seconds(1),
                    [this]{return threadToBeStopped;} ) == cv_status::no_timeout;
                std::cout << endIOThread << std::endl
            }
        }
        std::cout << "Exiting the Thread" << std::endl;
    }

public:
    thread                          threadRunner;
    MyClassWithThread()
    {
        threadRunner = thread(&MyClassWithThread::ThreadFunction, this);
    }
};

int main(int argc, char* argv[])
{
    MyClassWithThread myclassWithThread;
    myclassWithThread.threadRunner.join();
    return 0;
}

To build on Linux:

g++ -std=c++11 -pthread cond-wait-test.cpp -o cond-wait-test -lboost_system -lboost_thread -lboost_chrono

However, when i execute the code, all i notice is that the thread execution is blocked at the call to wait_for method; forever. despite the timeout period. Further, the resource monitor of the system shows a processor core is being 100% utilized.

Could anyone please explain whats happening in the code?


As suggested by @Zan Lynx, the culprit was #pragma pack statement. I initially used only #pragma pack(1) to byte align some structures. This affected many of mutex structures to 1 byte alignment.

I changed the #pragma pack(1) statements to #pragma pack(push, 1) #pragma pack(pop). Its all working fine. Hence my problem is solved; i learnt something. Thanks a Lot. ! :-)