ich in ein seltsames Problem kommen in Pthread Programmierung ich den folgenden Code in VS2005 mit pthread-w32VS rand() Problem mit 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;
}
und Ausgabe zusammengestellt haben, ist, wie diese
2:41
1:41
1:467
2:467
1:334
2:334
1:1000
2:1000
es ist einfach so rand() ist das gleiche Ergebnis in jeweils zwei Anrufe zurückkehren und ich habe srand(), aber das Ergebnis jedes Mal nicht ich das Programm laufen ändern
Ich bin sehr neu in Multi-Thread-Programmierung und ich habe gehört, dass der Rand() nicht threadsicher ist. aber ich kann immer noch nicht herausfinden, ob das obige Programm falsch ist oder die rand() Funktion ein Problem hat.
Verwandte SO Frage: [Ist Windows 'rand_s thread-safe?] (Http://stackoverflow.com/questions/143108/is-windows-rand-s-thread-safe) –