与pthread-win32的VS rand()问题

时间:2009-05-17 06:09:54

标签: c++ visual-studio random pthreads

我在pthread编程中遇到了一个奇怪的问题 我使用pthread-w32

在vs2005中编译了以下代码
#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;
}

和输出就像这样

2:41
1:41
1:467
2:467
1:334
2:334
1:1000
2:1000

就像rand()在每两次调用中返回相同的结果一样 我有srand()但每次运行程序时结果都不会改变

我对多线程编程很新,我听说rand()不是线程安全的。但我仍然无法弄清楚上面的程序是错误还是rand()函数有问题。

2 个答案:

答案 0 :(得分:4)

rand只是伪随机的,每次都会返回相同的序列。 srand仅适用于当前线程,因此在主线程中调用它不会影响您的工作线程。

您需要在每个帖子中调用srand,并为每个帖子添加不同的值 - 例如,在thread1thread2函数中:

srand((int)time(NULL) ^ (int)pthread_getthreadid_np());

答案 1 :(得分:1)

尝试使用rand_s()代替,它是线程安全的。见here。当然,它不便携。

相关问题