I have the following code to try (and fail) to protect a critical region in my code. Basically I want a print statement to be fully executed by any thread before some other thread prints another statement.
In main.h
:
pthread_mutex_t printer_mutex;
In main.c
- the first thing the program does:
pthread_mutex_init(&printer_mutex, NULL);
The threads are created like so (I've removed some of the checks though):
for(long t = 0; t < NUM_THREADS; t++) {
args[t].fw = fw;
args[t].deriv_init = deriv_init;
args[t].to_prove = fw.to_prove.at(i);
pthread_create(&threads[t], NULL, do_derivation_helper, (void *) &args[t]);
}
for(long t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
Then in a class of mine that does all the printing in the program I have the following. The printing should be locked and then unlocked when it is finished.
void InfoViewer::rule_x_fires() {
// START CRITICAL REGION
pthread_mutex_lock(&printer_mutex);
cout << "INFO: Rule x fires" << endl;
pthread_mutex_unlock(&printer_mutex);
// END CRITICAL REGION
}
The undesired output I get is:
INFO: Rule x firesINFO: Rule x fires
I.e. the line is not ended before some other thread starts printing.
Any ideas? Am I not initialising correctly? Am I ok using standard C style threads in my C++ program?