2 arrays of the same size are given. 2 threads need to be created, each responsible for 1 array, the threads should work at the same time. After both threads set one element (array_B[i] = ++count;), the arrays should be printed to the screen, wait for a key press, then the threads should continue, and so on.
I am not 100% sure if this should be solved with mutexes or not. It is working to a certain extent, but the program doesn't stop after 1 update for each array as it is intended.
pthread_mutex_t mutex_A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_B = PTHREAD_MUTEX_INITIALIZER;
int array_A[NMax], array_B[NMax];
void *fun_A(void *arg)
{
int count = 0;
for (int i = 0 ; i < NMax ; ++i)
{
pthread_mutex_lock(&mutex_A);
array_A[i] = ++count;
pthread_mutex_unlock(&mutex_A);
}
return NULL;
}
void *fun_B(void *arg)
{
int count = 0;
for (int i = 0 ; i < NMax ; ++i)
{
pthread_mutex_lock(&mutex_B);
array_B[i] = ++count;
pthread_mutex_unlock(&mutex_B);
}
return NULL;
}
void Print()
{
system("cls");
for (int i = 0 ; i < NMax ; ++i)
printf("%d ", array_A[i]);
printf("\n\n");
for (int i = 0 ; i < NMax ; ++i)
printf("%d ", array_B[i]);
getch();
}
int main()
{
pthread_t A_th, B_th;
pthread_create(&A_th, NULL, &fun_A, NULL);
pthread_create(&B_th, NULL, &fun_B, NULL);
while (1)
{
pthread_mutex_lock(&mutex_A);
pthread_mutex_lock(&mutex_B);
Print();
pthread_mutex_unlock(&mutex_A);
pthread_mutex_unlock(&mutex_B);
}
pthread_join(A_th, NULL);
pthread_join(B_th, NULL);
return 0;
}
pthread_cond_wait
andpthread_cond_broadcast
. – user3386109