【发布时间】:2021-11-15 04:12:13
【问题描述】:
代码如下:
#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int seed = 1;
int n =4;
int i = 0;
#pragma omp parallel for num_threads(4) private(seed)
for(i=0;i<n;i++)
{
int temp1 = rand_r(&seed);
printf("\nRandom number: %d by thread %d\n", temp1, omp_get_thread_num());
}
return 0;
}
代码输出为:
Random number: 1905891579 by thread 0
Random number: 1012484 by thread 1
Random number: 1012484 by thread 2
Random number: 1012484 by thread 3
这对我来说很奇怪:为什么线程 0 有不同的编号? 但是当我将 n 更改为 const 数字 4 时:
#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int seed = 1;
const int n =4;
int i = 0;
#pragma omp parallel for num_threads(4) private(seed)
for(i=0;i<n;i++)
{
int temp1 = rand_r(&seed);
printf("\nRandom number: %d by thread %d\n", temp1, omp_get_thread_num());
}
return 0;
}
代码输出为:
Random number: 1012484 by thread 2
Random number: 1012484 by thread 3
Random number: 1012484 by thread 0
Random number: 1012484 by thread 1
所有线程都有相同的随机数。 我不明白当 n 不是 const 变量时线程 0 具有不同数字的原因。 有没有人知道这件事?非常感谢。
【问题讨论】:
-
你确定这是一个“c++”问题吗? #include
的包含似乎表明您正在编写“C”代码。随机数是因为两次运行都使用相同的“种子”。对于 C++,请在此处查找随机数生成:en.cppreference.com/w/cpp/numeric/random/random_device。在 c++ 中也尽量避免使用 printf(这是不安全的:stackoverflow.com/questions/64042652/…)。 -
@PepijnKramer “随机数是 [...],因为两次运行都使用相同的“种子”。”是什么?完全相同的?根据 OP 的输出报价,它们不是。
-
@Yunnosch 在第一个版本的代码中,我使用相同的种子,但线程 0 得到不同的随机数。这很奇怪。
-
@PepijnKramer 在第一个版本的代码中,我使用相同的种子,但是线程 0 的随机数不同。这很奇怪
-
我知道。 Pepijn 似乎没有。
标签: c++