【问题标题】:VS rand() problem with pthread-win32pthread-win32 的 VS rand() 问题
【发布时间】:2009-05-17 06:09:54
【问题描述】:

我在 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()函数有问题。

【问题讨论】:

标签: c++ visual-studio random pthreads


【解决方案1】:

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

您需要在每个线程中调用 srand,每个线程的值都不同 - 例如,在您的 thread1thread2 函数中:

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

【讨论】:

  • 非常感谢,但我想知道为什么 srand() 只适用于当前线程?
  • 可能使用线程本地存储 - 每个线程都有自己的随机数种子副本
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多