I need to write two threads. Each of them prints 5 even / odd numbers from 1 to 100, like this (odd impairin French, even pair).
even 2,4,6,8,10
odd 1,3,5,7,9
even 12,14,16,18,20
odd 13,15,17,19,21
etc...
I wrote this code:
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#define maxi 100
pthread_mutex_t mutex;
sem_t p;
sem_t imp;
int tour = 0;
void *pair(void *arg);
void *impair(void *arg);
int main() {
pthread_t tidp, tidimp;
pthread_mutex_init(&mutex, NULL);
sem_init(&p, 0, 1);
sem_init(&imp, 0, 1);
pthread_create(&tidp, NULL, pair, (void *)2);
pthread_create(&tidimp, NULL, impair, (void *)1);
pthread_join(tidp, NULL);
pthread_join(tidp, NULL);
sem_destroy(&imp);
sem_destroy(&p);
pthread_mutex_destroy(&mutex);
return 0;
}
void *pair(void *arg) {
int i = (int)arg;
int j, l;
pthread_mutex_lock(&mutex);
if (!tour) {
tour = 1;
pthread_mutex_unlock(&mutex);
sem_wait(&imp);
} else {
pthread_mutex_unlock(&mutex);
}
for (l = 0; l < maxi; l += 10) {
sem_wait(&p);
printf(" Pair ");
pthread_mutex_lock(&mutex);
for (j = 0; j < 10; j += 2) {
printf(" %4d \t", j + i);
}
pthread_mutex_unlock(&mutex);
printf("\n");
sem_post(&imp);
i += 10;
}
pthread_exit(NULL);
}
void *impair(void *arg) {
int i = (int)arg;
int j, l;
pthread_mutex_lock(&mutex);
if (!tour) {
tour = 1;
pthread_mutex_unlock(&mutex);
sem_wait(&p);
} else {
pthread_mutex_unlock(&mutex);
}
for (l = 0; l < maxi; l += 10) {
sem_wait(&imp);
printf("Impair ");
pthread_mutex_lock(&mutex);
for (j = 0; j < 10; j += 2) {
printf(" %4d \t", j + i);
}
pthread_mutex_unlock(&mutex);
printf("\n");
sem_post(&p);
i += 10;
}
pthread_exit(NULL);
}
I don’t understand that when I run the code, sometimes it starts with odd, sometimes with even. More specifically, when it starts with odd, everything goes fine, and I get all numbers from 1 to 100, but when it starts with even, sometimes I get only 91, sometimes 93, sometimes 97.
Can someone tell me what is wrong? Below are the screenshots below.


