C++ cout crashes during concurrent usage with boost’s threads under embedded Linux

Last week I was testing my C++ concurrent priority queue for HTTP requests with std::cout printing on the console output for possible race conditions. I was running my unit tests for some potential problems, when I found out that there was a crash of a unit test under embedded Linux. The same code was tested under Windows 7 and I didn’t see any crash of all unit tests. I was very curious to find out the reason for this crash. Under suspicion was problem with memory allocation or something similar as usual, but I hadn’t any assertions for that. On the next morning I spent two hours experimenting with isolation of the problem code. It appears that std::cout is crashing when it’s used by threads printing on the Linux console. Test application given below is a simple example for the crash with two boost threads which are printing numbers using std::cout. Maybe it’s trivial case why this example is crashing but sometimes similar problems like this can lose more than a week in spaghetti code, when you don’t  expect crash from this kind. The used embedded Linux for testing is BusyBox and the code is executed by processor with MIPS architecture.

int main(int argc, char* argv[] )
{
    boost::thread thOne(coutOne);
    boost::thread thTwo(coutTwo);
    thOne.join();
    thTwo.join();
    return 0;
}
void coutOne()
{
    for(int i = 0; i < 10000; i++)
    {
        std::cout << " coutOne : " << i << std::endl;
    }
}
void coutTwo()
{
    for(int i = 0; i < 10000; i++)
    {
        std::cout << " coutOne : " << i << std::endl;
    }
}

2 thoughts on “C++ cout crashes during concurrent usage with boost’s threads under embedded Linux

Leave a Reply

Your email address will not be published. Required fields are marked *