I have a program that spawns a number of threads. Each thread generates a table of output. During the time that it is creating this output, I don't want the other threads to be outputting, so I've attempted to create a mutex semaphore to allow only one thread at time to ouput.
Code:
sem_t mutex;
void* node(void *thread_arg) {
...
// set a mutex lock to allow the output for this next step to complete for this thread
sem_wait(&mutex);
// generate table with various fprintf statements
sem_post(&mutex);
...
}
int main(int argc, char *argv[]) {
...
// semaphore to allow the output to organize correctly
sem_init(&mutex, 0, 1);
// spawn a separate thread for each host
for (i = 0; i < NUM_HOSTS; i++) {
host_thread[i] = (pthread_t *) malloc(sizeof(pthread_t));
if (verbose) printf ("In main, spawning thread for host %d\n", i);
int rc = pthread_create (host_thread[i], NULL, node, (void *) &thread_data_array[i]);
if (rc)
printf("ERROR: return code from pthread_create() is %d for host thread %d\n", rc, i);
}
...
}
This approach isn't working. Can anyone set me on the right path? Thanks!