samedi 22 avril 2023

Using srand with pthread generate the same number in C

I'm trying to run this very simple code which generate a random number between 0 to 99 using multithreading:

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


void * NumGen(void * tid){
    int a = 0;
    a = rand() % 100;
    printf("a: %d\n",a);
};

int main()
{
    srand(time((NULL)));
    pthread_t tid0;
    pthread_t tid1;
    pthread_t tid2;
    pthread_t * pthreads[] = {&tid0,&tid1,&tid2};

    for (int i = 0; i < 3; i++)
        pthread_create(pthreads[i],NULL,NumGen,NULL);

    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}

Although I used srand(time((NULL))), the output I get is:

a: 41
a: 41
a: 41

What is the reason that I don't get different number each time? Thanks




Aucun commentaire:

Enregistrer un commentaire