c++ - 为并行化的 for() 循环提供线程私有(private)预分配缓冲区?

标签 c++ visual-studio-2008 openmp

我的程序包含一个 for() 循环,它逐行处理一些原始图像数据,我想像这样使用 OpenMP 对其进行并行处理:

...
#if defined(_OPENMP)
        int const  threads = 8;
        omp_set_num_threads( threads );
        omp_set_dynamic( threads );
#endif
        int line = 0;
#pragma omp parallel private( line )
        {
            // tell the compiler to parallelize the next for() loop using static
            // scheduling (i.e. balance workload evenly among threads),
            // while letting each thread process exactly one line in a single run
#pragma omp for schedule( static, 1 )
            for( line = 0 ; line < max; ++line ) {
                // some processing-heavy code in need of a buffer
            }
        } // end of parallel section
....

问题是这样的:

是否可以使用标准 OpenMP pragma/function 为团队中执行我的循环的每个线程提供一个单独的(预分配的)缓冲区(指针)(从而无需分配新的缓冲区每个循环)?

提前致谢。

比约恩

最佳答案

我可能理解错了,但我认为应该这样做:

#pragma omp parallel 
{
    unsigned char buffer[1024]; // private

    // while letting each thread process exactly one line in a single run
    #pragma omp for // ... etc
    for(int line = 0; line < max; ++line ) {
          //...
    }
}

如果您真的想为不同的并行 block ​​共享相同的缓冲区,您将不得不求助于线程本地存储。 (与直接使用 TlsAlloc 和 friend 相比,Boost 和 C++11 具有使这更容易完成(也更便携)的设施)。

注意,这种方法取代了程序员的一些线程安全检查负担,因为完全有可能同时运行不同的 omp parallel 部分,尤其是当它们被嵌套时。

考虑到并行 block 可以在运行时嵌套,即使它们不是词法嵌套。在实践中,这通常不是好的风格 - 并且通常会导致性能不佳。但是,执行此操作时需要注意这一点)。

关于c++ - 为并行化的 for() 循环提供线程私有(private)预分配缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7837642/

相关文章:

c++ - 错误消息 : "Assertion ' t = find_next_time_event( m )' failed at pulse/mainloop.c" ? ...(C++)

c++ - 预编译头文件和预编译二进制文件有什么区别

visual-studio-2008 - Visual Studio 2008 Emacs 模式

c++ - 使用从 DLL 导出的 MFC90 类和用 MFC100 构建的 DLL

c# - 使用 C# 获取特定 XML 元素值的问题

c - 如何在 OpenMP 中获取和释放锁

c++ - OMP - 线程数多于处理器数?

c++ - 删除继承中的内存

c - 临界区的开销超过 for 循环并行化的加速

c++ - QML 绑定(bind)不更新