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.
| C++ | | copy code | | ? |
| 01 | int main(int argc, char* argv[] ) |
| 02 | { |
| 03 | boost::thread thOne(coutOne); |
| 04 | boost::thread thTwo(coutTwo); |
| 05 | |
| 06 | thOne.join(); |
| 07 | thTwo.join(); |
| 08 | |
| 09 | return 0; |
| 10 | } |
| 11 | |
| 12 | void coutOne() |
| 13 | { |
| 14 | for(int i = 0; i < 10000; i++) |
| 15 | { |
| 16 | std::cout << " coutOne : " << i << std::endl; |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | void coutTwo() |
| 21 | { |
| 22 | for(int i = 0; i < 10000; i++) |
| 23 | { |
| 24 | std::cout << " coutOne : " << i << std::endl; |
| 25 | } |
| 26 | } |