我应该给一个数字传递给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));
...
init赛车的代码生成“随机种子”
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));
}
}
答案 0 :(得分: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;
}