mardi 3 février 2015

Insert and alter a random number in pthread_create

I have this function to generate a random number.



int rand_lim(int limit) {
// return a random number between 0 and limit inclusive.
int divisor = RAND_MAX/(limit+1);
int retval;
srand(time(NULL));
do {
retval = rand() / divisor;
} while (retval > limit);

return retval;
}


i call it like this:



srand(time(NULL));
int decrease = -rand_lim(10);


in order to get a random negative number up to 10.


Then when i call a pthread_create:



pthread_create(&thread,attr, change_number_thread, (void *)&decrease);


I want the number to be different every time.


The change_number_thread function is the below:



void * change_number_thread(void *n) // increments the x by i forever and prints it with delay (using delay function)
{
int *i = (int*)n;
while (1) // This way it loops forever
{ printf("Thread adjustment = %2i; x = %i\n", *i, x);
x += *i;
delay(rand()%MAXDELAY);
}
return n;


I can get a random number but because the pthread_create is in a loop i wish to have a different time every time.


Any thoughts?





Aucun commentaire:

Enregistrer un commentaire