I have a barrier problem task in which N threads have to increment a number X. When all are done incrementing, the last thread will print a message. I understand the need to use semaphores for syncing them to the last thread but why do we need to sync them amongst each other? They're all performing the same function and the order does not matter.
Here's the part of the question confusing me:
Make use of semaphores to synchronize the access to x. Also use a semaphore to prevent the special thread from printing the required statement until the n threads have finished. The values of x will be printed in order. Do not use semaphores in the main function; use them in the threads created.
Here's the code I have written:
sem_t mutex, barrier;
int x=0, count=0, n=0;
void* PrintMessage(void* a)
{
sem_wait(&barrier);
printf("All threads have finished their execution \n");
sem_post(&barrier);
pthread_exit(0);
}
void* Increment(void* a)
{
sem_wait(&mutex);
x=x+1;
printf("%d \n", x);
count=count+1;
sem_post(&mutex);
if(count==n)
sem_post(&barrier);
pthread_exit(0);
}
int main(int argc, char* argv[])
{
sem_init(&mutex, 0, 1);
sem_init(&barrier, 0, 0);
n=atoi(argv[1]);
pthread_t finalthread;
pthread_create(&finalthread, NULL, PrintMessage, NULL);
pthread_t threads[n];
for(int i=0; i<n; ++i)
{
pthread_create(&threads[i], NULL, Increment, NULL);
pthread_join(threads[i], NULL);
}
pthread_join(finalthread, NULL);
sem_destroy(&mutex);
sem_destroy(&barrier);
}