【C++】——windows cmake openmp支持测试

参考:https://www.jianshu.com/p/f7e11b2df847

1. 安装pthread

通过链接ftp://sourceware.org/pub/pthreads-win32/pthreads-w32-2-8-0-release.exe下载pthreads安装文件,双击这个文件将其解开,然后将解开后的Pre- built.2/lib文件夹中的ibpthreadGC2.a改名为libpthread.a复制到MinGW目录的lib目录中,将Pre- built.2/include文件夹中的pthread.h
文件复制到MinGW目录的include目录中即可。

2. cmakelists

在其中添加 set(CMAKE_CXX_FLAGS "-fopenmp")

3. 测试demo

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

void Hello(void);

int main(int argc, char* argv[]) {
    int thread_count = 10;
#pragma omp parallel for
    for (int i = 0; i < thread_count; ++i) {
        printf("current value:%d in %d \n", i, thread_count);
    }

#  pragma omp parallel num_threads(thread_count)
    Hello();
    getchar();
    return 0;
}

void Hello(void) {
    int my_rank = omp_get_thread_num();
    int thread_count = omp_get_num_threads();

    printf("Hello from thread %d of %d\n", my_rank, thread_count);
}

输出的index会具有随机性,就表示正确了。输出:

current value:2 in 10
current value:7 in 10
current value:5 in 10
current value:8 in 10
current value:6 in 10
current value:9 in 10
current value:4 in 10
current value:0 in 10
current value:3 in 10
current value:1 in 10
Hello from thread 3 of 10
Hello from thread 4 of 10
Hello from thread 7 of 10
Hello from thread 8 of 10
Hello from thread 0 of 10
Hello from thread 1 of 10
Hello from thread 2 of 10
Hello from thread 5 of 10
Hello from thread 6 of 10
Hello from thread 9 of 10

猜你喜欢

转载自blog.csdn.net/u011622208/article/details/107437059
今日推荐