【发布时间】:2014-03-05 09:10:59
【问题描述】:
我正在尝试执行以下代码并期望第一个 for 循环被划分为 2 个工作正常的线程,
第二个 for 循环将在“整个”中执行 2 次,即由线程 0 以及线程 1 执行,这在输出中没有发生。
omp_set_num_threads(2);
#pragma omp parallel
{
#pragma omp for
for(i=65;i<91;i++)
printf("%c ",i);
printf("\n\n");
//if(omp_get_thread_num()==1) //if enalbled then prints all a->z letters
{
for(i=97;i<123;i++){
printf("%c %d",i,omp_get_thread_num());
#pragma omp flush
}
}
#pragma omp barrier
}
运行 1
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a 1b 1c 1d 1e 1f 1g 1h 1i 1j 1k 1l 1m 1n 1o 1p 1q 1r 1s 1t 1u 1v 1w 1x 1y 1z 1
a 0b 0c 0d 0e 0f 0g 0h 0i 0j 0k 0l 0m 0n 0o 0p 0q 0r 0s 0t 0u 0v 0w 0x 0y 0z 0
运行 2
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a 0b 0c 0d 0e 0f 0g 0
a 1b 1c 1d 1e 1f 1g 1h 1i 1j 1k 1l 1h 0n 0o 0p 0q 0r 0s 0t 0u 0v 0w 0x 0y 0z 0m 1
那么线程 1 没有打印所有 a-z 的原因可能是什么? 可能会发生切换,但是,因为“隐式”障碍存在于并行构造的末尾 所以线程 1 -thread0 必须互相等待完成。
我尝试了 8-9 次运行,发现线程 1 始终无法打印其预期输出!
启用 if 条件 thread1 在每次运行时成功打印 a-z(检查 12 次!!)
【问题讨论】:
-
因为您在
i中存在竞争条件。将其设为私有。
标签: c++ c multithreading parallel-processing openmp