In my game there are two (relevant for this problem) threads (both are joinable), one is player and one is shot. When the thread player is created, the start routine function is called, in which the shot thread is created. In that function, there is a while loop in which the user decides the direction of movement on the map or shot, in the case of a shot, I create shot thread and the player should move while the shot is active, while only one shot at a time can be active. My problem is, when I use the pthread_join
function on the shot (to execute one shot at a time) where I create a shot thread, the player remains frozen. My question is, where is the right place to use pthread_join
without it interfering with player movement. I have already tried to use join in the start routine function of the shot thread, and in the main program (main), none of it works as it should. (the code example serves only as an approximate representation of what happens in the program).
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_t player_tid;
pthread_t shot_tid;
int life_points = 100;
typedef struct
{
unsigned char x_;
unsigned char y_;
unsigned char type_;
unsigned char index_;
} parametars;
void *placeShot(parametars *params)
{
// TODO start: find if shot hit an alien, remove shot and alien if so. // Hint: I have already implemented that, works fine.
printf("Shot coordinates: %d, %d", params->x_, params->y_);
free(params);
// TODO end;
return NULL;
}
void *playerLogic()
{
int c;
while (life_points > 0)
{
char shot = 0;
c = getchar();
switch (c)
{
case ' ':
shot = 1;
break;
default:
break;
}
if (c == 'q')
{
life_points = 0;
continue;
}
// TODO start: spawn the shot and make sure to wait until the last shot is //finished
parametars *params;
if (shot)
{
params = malloc(sizeof(parametars));
params->x_ = 3;
params->y_ = 2;
if (pthread_create(&shot_tid, NULL, (void *(*)(void *)) & placeShot, params) != 0)
{
printf("Failed to create shot thread");
}
}
// TODO end
}
return NULL;
}
int main()
{
// TODO create a player thread with already provided resources
if (pthread_create(&player_tid, NULL, (void *(*)(void *)) & playerLogic, NULL) != 0)
printf("Failed to create player thread");
if (pthread_join(player_tid, NULL) != 0)
printf("Failed to join player thread");
return 0;
}