Using OpenMP (一) Write a multi threaded program

来源:互联网 发布:java的四大特性 编辑:程序博客网 时间:2024/05/29 18:05

Using OpenMP (一)  Write a multi threaded program

2017/10/22

 

 by

CHENJING DING

 


CHAPTER2 – 共享变量和私有变量


How to use OpenMP in Visual Studio

1.       Start“new project”

2.       Selectwin 32 console project

3.       Setname and path

4.       Onthe next panel, click “next” instead of finish so you can select an emptyproject on the following panel.

5.       Dragand drop your source file into the source folder on the visual studio solutionexplorer

6.       ActivateOpenMP– Go to project properties/configuration properties/C. C++/language … andactivate OpenMP

7.       Setnumber of threads inside the program

omp_set_num_threads(4);

8.       Buildthe project

9.       Run“without debug” from the debug menu.


Write a multithreadedprogram

 #include <iostream>   #include "omp.h"    using namespace std;   int main(int argc, char **argv) {        //设置线程数,一般设置的线程数不超过CPU核心数,这里开4个线程执行并行代码段       omp_set_num_threads(4);    #pragma omp parallel       {          cout << "Hello" << ", I am Thread " << omp_get_thread_num() << endl;  //获取当前进程号    }   }  


头文件

#include "omp.h"

格式

#pragma omp parallel  

{  

//每一段代码每一个线程都会执行一遍

}

结果

Hello, I am Thread 1  Hello, I am Thread 0  Hello, I am Thread 2  Hello, I am Thread 3  


四个线程都执行了大括号里的代码,先后顺序不确定,这就是一个并行块

带有for的制导指令

for制导语句是将for循环分配给各个线程执行,这里要求数据不存在依赖

 使用形式为:

(1)#pragma omp parallel for

        for(){}

(2)#pragma omp parallel

       {//注意:大括号必须要另起一行

        #pragma omp for

         for(){}

       }

作用域

第一种作用域只是紧跟着的那个for循环,而第二种形式在整个并行块中可以出现多个for制导指令。比如:

  #pragma omp parallel       {    #pragma omp for           for (int i = 0; i < 6; i++)                printf("i = %d, I am Thread %d\n", i, omp_get_thread_num());   #pragma omp master            {               //这里的代码由主线程执行                printf("I am Thread %d\n", omp_get_thread_num());          }   #pragma omp for          for (int i = 0; i < 6; i++)               printf("i = %d, I am Thread %d\n", i, omp_get_thread_num());      }  


 由于用parallel标识的并行块中每一行代码都会被多个线程处理,所以如果想让两个for循环之间的代码由一个线程执行的话就需要在代码前用single或master制导语句标识,master由是主线程执行,single是选一个线程执行,这个到底选哪个线程不确定

原创粉丝点击