Where should i put the lock and unlock mutex in order for the threads to print alternatively? Thanks:D
Implement a program that creates two threads. The threads will print their ID (pthread_self) 10 times and then stop. Insure that the printed IDs alternate always (ie A, B, A, B, ...)
#include <stdio.h>
#include <pthread.h>
#define N 2
pthread_mutex_t mtx;
void* func (void* arg) {
int i=0;
int f=1;
for(i=0; i<10; i++) {
printf("%d%s%d\n",f ,": ", (int)pthread_self());
f++;
}
return NULL;
}
int main() {
int i;
pthread_t thr[N];
pthread_mutex_init(&mtx, NULL);
for(i=0; i<N; i++) {
pthread_create(&thr[i], NULL, func, NULL);
}
for(i=0; i<N; i++) {
pthread_join(thr[i], NULL);
}
pthread_mutex_destroy(&mtx);
return 0;
}