c - 函数依赖 openMP

标签 c multithreading performance parallel-processing openmp

我有 5 个函数 A、B、C、D、E。
要执行 D,我需要执行 B、C,
要执行 E 我需要执行 A、D。
我试过这个

int main()
{
    #pragma omp parallel num_threads(5) 
    {
        long t1 = clock();
        int a = 0, b = 0, c = 0, d = 0, e = 0;
        int th = omp_get_thread_num();
        if (th == 0) {
            a += A();
            printf("A is finished after %d\n", clock() - t1);
        }
        if (th == 1) {
            b += B();
            printf("B is finished after %d\n", clock() - t1);
        }
        if (th == 2) {
            c += C();
            printf("C is finished after %d\n", clock() - t1);
        }
        if (th == 3 && (b == 1 && c == 1)) {
            d += D();
            printf("D is finished after %d\n", clock() - t1);
        }
        if (th == 4 && (a == 1 && d == 1)) {
            e += E();
            printf("E is finished after %d\n", clock() - t1);
        }

    }
    return 0;
}
但是D、E还没有执行
到目前为止,所有这些函数都返回 1 用于调试目的

最佳答案

一个合适的 OpenMP 解决方案是使用具有数据依赖性的任务:

    #pragma omp parallel num_threads(3)
    #pragma omp single
    {
        double t1 = omp_wtime();
        int a = 0, b = 0, c = 0, d = 0, e = 0;
        #pragma omp task shared(a) depend(out: a)
        {
            a += A();
            printf("A is finished after %f\n", omp_wtime() - t1);
        }
        #pragma omp task shared(b) depend(out: b)
        {
            b += B();
            printf("B is finished after %f\n", omp_wtime() - t1);
        }
        #pragma omp task shared(c) depend(out: c)
        {
            c += C();
            printf("C is finished after %f\n", omp_wtime() - t1);
        }
        #pragma omp task shared(b,c,d) depend(in: b,c) depend(out: d)
        {
            d += D();
            printf("D is finished after %f\n", omp_wtime() - t1);
        }
        #pragma omp task shared(a,d,e) depend(in: a,d)
        {
            e += E();
            printf("E is finished after %f\n", omp_wtime() - t1);
        }

    }
在这里,任务Aa 的值标记为生产者与 depend(out: a)和任务D被标记为 d 的生产者与 depend(out: d) .任务 E被标记为这两个值的消费者 depend(in: a,d) .在输出(生产者)和输入(消费者)依赖之后,OpenMP 运行时构建一个执行 DAG(有向无环图),告诉它所有任务的正确执行顺序。您也不需要五个线程 - 三个就足够了。
single 中包含任务代码构造是非常惯用的 OpenMP。
OpenMP 4.0 早在 2013 年就引入了任务依赖项,因此除 MSVC++ 之外的任何现代编译器都应提供对该功能的支持。

关于c - 函数依赖 openMP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64987301/

相关文章:

我可以让 fgets() 只接受字母吗?

c - C中从父进程到子进程连续写入

java - 进程 p = Runtime.getRuntime().exec() 将异步运行?

objective-c - Objective C 是适合 3D 游戏的语言吗?

performance - F# Pick 基于输入的函数?

c - 如何使用 C 程序读取来自端口的 UDP 数据负载

java - C服务器和Java客户端之间的UDP连接

c# - Thread.Sleep() 窃取调试器焦点

c - 线程在函数返回后停止

python - 如何有效地浏览和比较非常大的字典的值与列表的元素?