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; } }
Is the cout object thread-safe? Is there a thread-safe version of the library you use?
There isn’t thread safe cout implementation under embedded Linux and Windows as I know.