Ralf17 Ralf17 - 1 month ago 15
C Question

Stimulate a racing game using threads

I'm trying to race 6 snails in a 100m track using threads. Here's the whole code http://ideone.com/An30s4. Why do some of the snails do not run at all? Why do
they don't finish the 100m track? (I actually want all of them to reach the finish line. Then I'll print the winners at the end of the program.)

struct snail_thread{
int move;
char snail_name[10];
char owner[10];
};

int sum = 0;

void printval(void *ptr) {
struct snail_thread *data;
data = (struct snail_thread *) ptr;

while(sum < 100) {
sum += data->move;
printf("%s moves %d mm, total: %d\n",data->snail_name, data->move, sum);
}

pthread_exit(0);
}

int main(void) {
pthread_t t[6];
struct snail_thread s[6];
int i;

srand(time(NULL));

for(i = 0; i < 6; i++)
s[i].move = rand() % ((5 + 1) - 1) + 1;

strcpy(s[0].snail_name, "Snail A");
strcpy(s[0].owner, "Jon");

strcpy(s[1].snail_name, "Snail B");
strcpy(s[1].owner, "Ben");

strcpy(s[2].snail_name, "Snail C");
strcpy(s[2].owner, "Mark");

strcpy(s[3].snail_name, "Snail D");
strcpy(s[3].owner, "Jon");

strcpy(s[4].snail_name, "Snail E");
strcpy(s[4].owner, "Mark");

strcpy(s[5].snail_name, "Snail F");
strcpy(s[5].owner, "Ben");


for(i = 0; i < 6; i++)
pthread_create(&t[i],NULL,(void *) &printval, (void *) &s[i]);

for(i = 0; i < 6; i++)
pthread_join(t[i], NULL);

return (0);
}

Answer

Because your sum is global and all snails are incrementing it.

Put sum also in the struct.

Another little tip, for nicer results, make the move random for each step. Now the move is the same as the speed and you can know who wins without racing.

(And come on, give your snails better names than "Snail A" ;-)).

Comments