0

我应该得到一个数字来传递给 thread_mutex 初始化函数,以用作 usleep() 的 rondom 种子生成器。我不知道为随机数创建种子意味着什么。我在使用 srand() 时遇到的问题是将代码:srand(timeDelay)放在 for 循环中会使 rand() 始终相同。直接指示说:

This action happens repetitively, until its position is at FINISH_LINE:
//   Randomly calculate a waiting period, no mare than MAX_TIME (rand(3))
//   Sleep for that length of time.
//   Change the display position of this racer by +1 column*:
//     Erase the racer's name from the display.
//     Update the racer's dist field by +1.
//     Display the racer's name at the new position.

代码

int main( int argc, char *argv[] ) {
...
long int setDelay = strtol(argv[1], &pEnd, 10);
if ( setDelay == 0 ) {  
        //printf("Conversion failed\n");
        racersNumber = argc-1;
        setDelay = 3;
...
} else {
        //printf("Conversion SSS\n");
        racersNumber = argc-2;
        }
...
initRacers( setDelay);
for (idx = 0; idx < racersNumber; idx++) {
            printf("Thread created %s\n", racersList[idx]);
            //make a racer arra or do I add a pthread make function?
        rc = pthread_create(&threads[idx], NULL, run, (void*) makeRacer(racersList[idx], idx+1));
...

初始化赛车手生成“随机种子”的代码

static pthread_mutex_t mutex1;
static long int timeDelay;

void initRacers( long distance) {
    printf("Setting the time delay\n");
    //set the mutex

    pthread_mutex_init(&mutex1, NULL);
    timeDelay = distance; 
}

运行函数代码

#define MAX_TIME 200 // msec
void *run( void *racer ){
    //pre-cond: racer is not NULL
    if ( racer == NULL ) {
        return -1;
    }
    //convert racer back to racer
    for (int col = 0; col < FINISH_LINE; col++ ) {

        Racer *rc;
        //conversion
        rc= (Racer*)racer;
        pthread_mutex_lock(&mutex1);

        if ( col != 0 ) {
            set_cur_pos(rc->row, col-1);
            put(' ');
        }
        set_cur_pos( rc->row, col);
        pthread_mutex_unlock( &mutex1 );
        //loop function for each at same column
        for (int idx = 0; idx < sizeof(rc->graphic); idx++) {
            put(rc->graphic[idx]);
        }

        //srand(timeDelay);
        usleep(100000L*(rand()%timeDelay));

    }
}   
4

1 回答 1

0

将代码: srand(timeDelay) 放入 for 循环”。你不要srand()陷入循环。您在程序开始时调用它一次,通常带有时间参数,因此每次运行程序时从 rand() 获得的随机序列都是不同的。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main()
{
    int i;
    srand ((unsigned)time(NULL));
    for (i=0; i<5; i++)
        printf ("%6d", rand());
    printf ("\n");
    return 0;
}
于 2014-12-05T08:27:07.827 回答