Hey everyone, I found a really, really weird bug! I'm making a multithreaded application, and for some reason, the program just quits halfway through, always in different spots!
And get this, it only starts working when I remove the cout in join()!
Code:
#include <pthread.h>
#include <cassert>
#include <iostream>
using namespace std;
class Thread {
protected:
static void *pthreadMain(void *args) {
return ((Thread *)args)->main();
}
void *main() { return NULL; }
pthread_t thread;
public:
void jumpIntoNewThreadAndStart() {
int error = pthread_create(&thread, NULL, pthreadMain, this);
assert(error == 0);
}
void join() {
std::cout << __FILE__ << ":" << __LINE__ << std::endl;
void *returnValue = NULL;
int error = pthread_join(thread, &returnValue);
assert(error == 0);
}
};
int main() {
for (int i = 0; i < 100; i++) {
std::cout << "trial " << i << std::endl;
Thread thread;
thread.jumpIntoNewThreadAndStart();
thread.join();
}
std::cout << "done!" << std::endl;
}
As you can see, it does 100 trials. On occasion it gets through all of them, but most of the time, it dies before it gets halfway through them. My latest run of the program only made it to 13:
Code:
trial 0
..\TestWFMO.cpp:25
trial 1
..\TestWFMO.cpp:25
trial 2
..\TestWFMO.cpp:25
trial 3
..\TestWFMO.cpp:25
trial 4
..\TestWFMO.cpp:25
trial 5
..\TestWFMO.cpp:25
trial 6
..\TestWFMO.cpp:25
trial 7
..\TestWFMO.cpp:25
trial 8
..\TestWFMO.cpp:25
trial 9
..\TestWFMO.cpp:25
trial 10
..\TestWFMO.cpp:25
trial 11
..\TestWFMO.cpp:25
trial 12
..\TestWFMO.cpp:25
trial 13
..\TestWFMO.cpp:25
It's odd that when I comment out the std::cout in join(), it always makes it all the way through.
Definitely the weirdest bug I've ever seen. This thing has had me banging my head against the wall for days.
Anyone have any ideas?