OpenMP 共享变量似乎是私有的
OpenMP shared variable seems to be private
我不明白为什么在这段代码中只有线程 0 有 n = 1 而其他线程有 n = 0 与 shared n:
int main()
{
int n, tid;
#pragma omp parallel shared(n) private(tid)
{
tid = omp_get_thread_num();
n = 0;
if (tid == 0)
{
n++;
}
printf("I'am %d, this is my n: %d\n", tid, n);
}
return 0;
}
输出:
I'am 5, this is my n: 0
I'am 7, this is my n: 0
I'am 0, this is my n: 1
I'am 2, this is my n: 0
I'am 4, this is my n: 0
I'am 3, this is my n: 0
I'am 6, this is my n: 0
I'am 1, this is my n: 0
我是 OMP 库的新手。我在一个有 8 个节点的集群上通过 ssh 工作,这可能是问题所在吗?
谢谢。
您实际上是通过每个线程将 n
重置为零。只有带有 tid==0
的线程才会在打印前递增 n
。即使在这里,您可能会遇到打印
的程序
I'am 0, this is my n: 0
而不是预期的
I'am 0, this is my n: 1
既然你产生了所谓的race condition.
如果您打算仅在运行时开始时将 n
初始化为零,则需要更早地初始化 n
,例如在开始并行部分之前:
n = 0;
#pragma omp parallel shared(n) private(tid)
{
tid = omp_get_thread_num();
if (tid == 0)
{
n++;
}
printf("I'am %d, this is my n: %d\n", tid, n);
}
但是请注意,打印列表中 n
的状态将再次变得有些随机,因为您永远无法确定线程 0 何时将 n
的值递增到等于 1 .
最后这应该是让每个线程打印的代码 "n=1":
int main()
{
int n=0, t;
#pragma omp parallel shared(n) private(t)
{
t = omp_get_thread_num();
if (t == 0)
{
n++;
}
#pragma omp barrier
printf("Sono %d e ho n = %d\n", t, n);
}
return 0;
}
感谢 fuesika。
我不明白为什么在这段代码中只有线程 0 有 n = 1 而其他线程有 n = 0 与 shared n:
int main()
{
int n, tid;
#pragma omp parallel shared(n) private(tid)
{
tid = omp_get_thread_num();
n = 0;
if (tid == 0)
{
n++;
}
printf("I'am %d, this is my n: %d\n", tid, n);
}
return 0;
}
输出:
I'am 5, this is my n: 0
I'am 7, this is my n: 0
I'am 0, this is my n: 1
I'am 2, this is my n: 0
I'am 4, this is my n: 0
I'am 3, this is my n: 0
I'am 6, this is my n: 0
I'am 1, this is my n: 0
我是 OMP 库的新手。我在一个有 8 个节点的集群上通过 ssh 工作,这可能是问题所在吗?
谢谢。
您实际上是通过每个线程将 n
重置为零。只有带有 tid==0
的线程才会在打印前递增 n
。即使在这里,您可能会遇到打印
I'am 0, this is my n: 0
而不是预期的
I'am 0, this is my n: 1
既然你产生了所谓的race condition.
如果您打算仅在运行时开始时将 n
初始化为零,则需要更早地初始化 n
,例如在开始并行部分之前:
n = 0;
#pragma omp parallel shared(n) private(tid)
{
tid = omp_get_thread_num();
if (tid == 0)
{
n++;
}
printf("I'am %d, this is my n: %d\n", tid, n);
}
但是请注意,打印列表中 n
的状态将再次变得有些随机,因为您永远无法确定线程 0 何时将 n
的值递增到等于 1 .
最后这应该是让每个线程打印的代码 "n=1":
int main()
{
int n=0, t;
#pragma omp parallel shared(n) private(t)
{
t = omp_get_thread_num();
if (t == 0)
{
n++;
}
#pragma omp barrier
printf("Sono %d e ho n = %d\n", t, n);
}
return 0;
}
感谢 fuesika。