c++ - 并行 vector 调整大小不加速

标签 c++ multithreading parallel-processing multiprocessing openmp

我必须使用 8 个处理器。 我想按如下方式进行并行调整大小:

    vector<vector <int> > test;
    test.resize(10000);
    #pragma omp parallel num_threads(8)
    {
        #pragma omp for
        for (int i = 0;i < 10000;i++)test[i].resize(500000);
    }

我注意到该程序并没有使用 100% 的处理器能力——它只使用了 15%。当我更改代码时

    vector<vector <int> > test;
    test.resize(1000000);
    #pragma omp parallel num_threads(8)
    {
        #pragma omp for
        for (int i = 0;i < 1000000;i++)test[i].resize(5000);
    }

程序使用了大约 60% 的处理器能力。我不明白这种现象——我希望它在这两种情况下都能使用 100% 的处理器能力。我在这里遗漏了什么吗?

最佳答案

在 Windows 上,CRT 使用内置的 Windows 堆实现,它是单线程的。

HeapAlloc在分配期间锁定一个 CriticalSection(本质上是一个互斥体),本质上是顺序分配过程。

由于 vector 大小调整主要是堆(重新)分配,因此并行化不会带来太大改进。

Serialization ensures mutual exclusion when two or more threads attempt to simultaneously allocate or free blocks from the same heap.

Setting the HEAP_NO_SERIALIZE value eliminates mutual exclusion on the heap. Without serialization, two or more threads that use the same heap handle might attempt to allocate or free memory simultaneously, likely causing corruption in the heap.

要从并行内存分配中获益,请使用不同的堆分配器。例如jemalloc .

关于c++ - 并行 vector 调整大小不加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54576576/

相关文章:

c++ - 每次调试此代码时,我都会收到 "subscript out of range error"。有人可以帮我查明错误或错误吗?

c++ - 谁能解释为什么我的 crypto++ 解密文件短 16 个字节?

c - 如何使用 swapcontext() 恢复函数的执行(而不是再次启动)?

c++ - cgi 中的进程处理

vb.net - 并行循环和 Nlog

c++ - 用一个元素初始化 vector 是否需要复制构造函数?

c++ - VS2010 中的 cout 分辨率

multithreading - 没有 AsyncTask,在后台运行线程并更新 UI 线程

c++ - std::thread constructor 传递指针和传递ref有区别吗?

ruby-on-rails - 在 Ruby 中并行运行命令行进程