简体   繁体   中英

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);
}

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" ;-)).

The thread body should be prototyped as void * printval (void * ptr) . Shutting up the compiler with casts is a shortcut to the highway to hell. And maybe given a more meaningful name. Posix is doing enough bad naming on its own, no need to help him getting you confused :).

But that's not the reason why your snails won't race. The reason is that the sum is a global variable, so all snails are competing to increment it. As soon as it reaches 100, all snails think they are done and exit.

Make sum a part of the thread context and it should work as intended.

EDIT: dang, I lost the race...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM