正在加载图片...
1 CHAPTER2 The OpenMP Memory Model In the following example,at Print 1,the value of x could be either 2 or 5,depending on the timing g of the threads,and the implementation of the assignment to x.There are two reasons that the value at Print I might not be 5.First,Print I might be executed before the assignment to x is executed. 67 ment.the value5 is not guaranteed to be seen by 8 The barrier after Print I contains implicit flushes on all threads,as well as a thread synchronization. so the programmer is guaranteed that the value 5 will be printed by both Print 2 and Print 3. C/C++ 10 Example mem_model.Io #include <stdio.h> #include <omp.h> int main()( int x; x=2; pragma omp parallel num_threads(2)shared(x) if (omp- -get_thread_num()=-0)( 85 fol ng read Thread#sd:x 819 S-18 s-19 #pragma omp barrier s-20 if (omp_get_thread_num()==0){1 CHAPTER 2 2 The OpenMP Memory Model 3 In the following example, at Print 1, the value of x could be either 2 or 5, depending on the timing 4 of the threads, and the implementation of the assignment to x. There are two reasons that the value 5 at Print 1 might not be 5. First, Print 1 might be executed before the assignment to x is executed. 6 Second, even if Print 1 is executed after the assignment, the value 5 is not guaranteed to be seen by 7 thread 1 because a flush may not have been executed by thread 0 since the assignment. 8 The barrier after Print 1 contains implicit flushes on all threads, as well as a thread synchronization, 9 so the programmer is guaranteed that the value 5 will be printed by both Print 2 and Print 3. C / C++ 10 Example mem_model.1c S-1 #include <stdio.h> S-2 #include <omp.h> S-3 S-4 int main(){ S-5 int x; S-6 S-7 x = 2; S-8 #pragma omp parallel num_threads(2) shared(x) S-9 { S-10 S-11 if (omp_get_thread_num() == 0) { S-12 x = 5; S-13 } else { S-14 /* Print 1: the following read of x has a race */ S-15 printf("1: Thread# %d: x = %d\n", omp_get_thread_num(),x ); S-16 } S-17 S-18 #pragma omp barrier S-19 S-20 if (omp_get_thread_num() == 0) { 4
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有