I was going to write a class which reads std::cin in a thread and calls a callback when something was entered. The callback is a boost::function. The code runs if I only have the std::getline (std::cin, command); , but crashes with "access violation" if I add the line if(this->m_receiveHandler != NULL). I really cannot find what's happening, so I reduced the problem down to the following test.
The problem is not fully deterministic, sometimes I can enter a line or two, sometimes it crashes immediately. The last thing the program outputs is always "access receiver handler".
class InputReader
{
private:
boost::function<void (const char*, unsigned int) > m_receiveHandler;
boost::thread m_receiveThread;
void receiveLoop(void)
{
while(true)
{
std::string command;
std::getline (std::cin, command);
std::cout << "access receiver handler" << std::flush;
if(this->m_receiveHandler != NULL)
{
}
}
}
public:
InputReader()
{
m_receiveThread = boost::thread(boost::bind(&InputReader::receiveLoop, this));
}
};
TEST(InputReaderTest, WaitInfinite)
{
InputReader reader;
while (true) {};
}
Do you see anything wrong with this code?
EDIT: I am compiling with GCC 4.3.2 on Suse Linux with Boost 1.49.
I've just tried this with clang on OSX and it works (replaced boost with std though). What happens when you start the thread in a different public member function? The boost function variable is in effect a shared variable between two threads and should probably be protected by some concurrency primitive. The thread might actually see an incomplete snapshot of the 'this' object. It doesn't explain why it works two times before failing though. If you know what the receiveHandler will be at construction time and you don't need to change it you have the option of passing the boost::function as a parameter to the thread (a copy or even a move might do).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With