并行化一系列独立的连续代码行

发布于 2024-11-03 19:20:16 字数 386 浏览 2 评论 0原文

如果多行代码彼此不依赖,并行执行它们的最佳方法是什么? (我正在使用 OpenMP)

伪代码:

database->connect()
openfile("stuff.txt")
ping("stackoverflow.com")
x = 2;
y = a + b;

我能想到的唯一方法是:

#pragma omp parallel for
for(i = 0; i < 5; i++)
switch (i) {
case 0: database->connect(); break;
...

我还没有尝试过,但我还记得你在使用 OpenMP 时不应该break

What is the best way to execute multiple lines of code in parallel if they are not dependent of each other? (I'm using OpenMP)

Pseudo code:

database->connect()
openfile("stuff.txt")
ping("stackoverflow.com")
x = 2;
y = a + b;

The only way I can come up with is:

#pragma omp parallel for
for(i = 0; i < 5; i++)
switch (i) {
case 0: database->connect(); break;
...

I haven't tried it, but I also remember that you're not supposed to break while using OpenMP

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风追烟花雨 2024-11-10 19:20:17

因此,我假设您列出的独立任务只是示例。如果它们确实是像 y=a+b 这样的东西,那么正如 @chrisaycock 和 @ejd 所说,它们对于这种并行性来说太小了(例如基于线程,而不是 ILP 或其他东西) )来实际利用由于开销而产生的并发性。但如果它们是更大的操作,则在 OpenMP 中执行基于任务的并行性的方法是使用 task 指令:例如,

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

void work(int *v) {
    *v = omp_get_thread_num();
    sleep(1);
}

int main(int argc, char **argv)
{
    int a, b, c;
    #pragma omp parallel
    {
        #pragma omp single
        {
            #pragma omp task shared(a) default(none)
            work(&a);

            #pragma omp task shared(b) default(none)
            work(&b);

            #pragma omp task shared(c) default(none)
            work(&c);
        }
    }
    printf("a,b,c = %d,%d,%d\n", a, b, c);

    return 0;
}

So I'm assuming that the indivdual things you listed as independant tasks were just examples. If they really are things like y=a+b, then as @chrisaycock and @ejd have said, they're too small for this sort of parallelism (eg thread based, as opposed to ILP or something) to actually take advantage of the concurrency due to overheads. But if they are bigger operations, the way to do task-based parallelism in OpenMP is with the task directive: eg,

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

void work(int *v) {
    *v = omp_get_thread_num();
    sleep(1);
}

int main(int argc, char **argv)
{
    int a, b, c;
    #pragma omp parallel
    {
        #pragma omp single
        {
            #pragma omp task shared(a) default(none)
            work(&a);

            #pragma omp task shared(b) default(none)
            work(&b);

            #pragma omp task shared(c) default(none)
            work(&c);
        }
    }
    printf("a,b,c = %d,%d,%d\n", a, b, c);

    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文