Je viens dans un étrange problème dans la programmation pthread j'ai compilé le code suivant dans VS2005 avec pthread-w32problème rand VS() avec pthread-win32
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <pthread.h>
#include <windows.h>
pthread_mutex_t lock;
void* thread1(void *) {
int r1;
while(true) {
pthread_mutex_lock(&lock); // rand is maybe a CS
r1 = rand() % 1500;
pthread_mutex_unlock(&lock);
Sleep(r1); printf("1:%d\n", r1);
}
return NULL;
}
void* thread2(void *) {
int r2;
while(true) {
pthread_mutex_lock(&lock);
r2 = rand() % 1500;
pthread_mutex_unlock(&lock);
Sleep(r2); printf("2:%d\n", r2);
}
return NULL;
}
int main() {
srand((int)time(NULL));
pthread_mutex_init(&lock, NULL);
pthread_t tc_p, tc_v;
pthread_create(&tc_p, NULL, thread1, NULL);
pthread_create(&tc_v, NULL, thread2, NULL);
pthread_join(tc_p, NULL);
pthread_join(tc_v, NULL);
pthread_mutex_destroy(&lock);
return 0;
}
et la sortie est comme ce
2:41
1:41
1:467
2:467
1:334
2:334
1:1000
2:1000
c'est comme si rand() retournait le même résultat dans tous les deux appels et j'ai srand() mais le résultat ne change pas chaque fois que je lance le programme
Je suis très nouveau à la programmation multi-threads et j'ai entendu parler du rand() n'est pas thread-safe. mais je n'arrive toujours pas à comprendre si le programme ci-dessus est faux ou si la fonction rand() a un problème.
Questions connexes: [Est-ce que Windows 'rand_s thread-safe?] (Http://stackoverflow.com/questions/143108/is-windows-rand-s-thread-safe) –