I'm trying to do a program in which there are two threads which talk like "pin-pong" way. The current result is the following:
the player 2 starts the game
1-I'm 139735290140224 and my ID is 2
2-I'm 139735290140224 and my ID is 2 and is turn of 1
3-I'm 139735290140224 and my ID is 2 and before the wait and turn is 1
1-I'm 139735298532928 and my ID is 1
2-I'm 139735298532928 and my ID is 1 and is turn of 2
3-I'm 139735298532928 and my ID is 1 and before the wait and turn is 2
4-I'm 139735290140224 and my ID is 2 and i'm after the wait and turn id 2
ID: 2, no boat ha drowned, coordinate(1,5)
and then it stops, while instead it should search in loop until one of the counter=10, so in this way:
the player 2 starts the game
1-I'm 139735298532928 and my ID is 2
2-I'm 139735298532928 and my ID is 2 and is turn of 1
3-I'm 139735290140224 and my ID is 1 and before the wait and turn is 2
4-I'm 139735290140224 and my ID is 1 and i'm after the wait and turn id 1
1-I'm 139735290140224 and my ID is 1
2-I'm 139735290140224 and my ID is 1 and is turn of 2
3-I'm 139735298532928 and my ID is 2 and before the wait and turn is 1
4-I'm 139735298532928 and my ID is 2 and i'm after the wait and turn id 2
..... and so on so far
Can somebody explain me how to use condition variables in a good and efficient way?
The program is this one:
void *battleship(void* index){
int n_boat = 17;
int ID_player=*(int*)index;
char matrix[10][10];
int matrix_drowned[10][10];
int cnt_1=0;
while(cnt<10){
while(turn==ID_player){
pthread_mutex_lock(&playerMutex);
while (cnt>0)
pthread_cond_wait(&check, &playerMutex);
game_over=0;
printf("1-I'm %lu and my ID is %d\n", pthread_self(), ID_player);
if (turn==1)
turn=2;
else
turn=1;
printf("2-I'm %lu and my ID is %d and is turn of %d\n", pthread_self(), ID_player, turn);
pthread_cond_signal(&your_turn);
pthread_mutex_unlock(&playerMutex);
}
pthread_mutex_lock(&playerMutex);
printf("3-I'm %lu and my ID is %d and before the wait and turn is %d\n", pthread_self(), ID_player, turn);
while(turn!=ID_player)
pthread_cond_wait(&your_turn, &playerMutex);
printf("4-I'm %lu and my ID is %d and i'm after the wait and turn id %d\n", pthread_self(), ID_player, turn);
cnt++;
game_over=1;
pthread_cond_signal(&check);
pthread_mutex_unlock(&playerMutex);
}
pthread_exit(NULL);
}