【问题标题】:multiple threads for vector processing用于向量处理的多线程
【发布时间】:2020-07-12 11:41:24
【问题描述】:

我有 2 个带有一些文件名和处理这些文件的函数的向量:

vector<string> vecFilenames1; // {filename1_1, filename1_2, filename1_3, ...}
vector<string> vecFilenames2; // {filename2_1, filename2_2, filename2_3, ...}

这些向量具有相同的大小。我现在如何处理:

// function for processing
void doSomeStuff() {// ...}
// processing loop
for (int i = 0; i < vecFilenames1.size();i++) {
    doSomeStuff(vecFilenames1[i], vecFilenames2[i]);
}

我有 4 个线程(2 个核心),我想更快地完成这样的过程,我该怎么做?

编辑 1

我使用mingw编译器:

g++ (MinGW.org GCC-8.2.0-5) 8.2.0
Copyright (C) 2018 Free Software Foundation, Inc.

我是否需要将其更改为较新的版本才能轻松解决我的问题?

编辑 2

我更新了我的 gcc:

g++.exe (MinGW.org GCC Build-2) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.

【问题讨论】:

  • 您应该指定最新版本的 C++ 以及可以使用的编译器,因为可能的答案之一是 std::for_each() 的并行重载,但这是 C++17 以后的版本仅,您的标准库实现可能支持也可能不支持该重载。
  • @underscore_d 我可以更改我的 mingw 版本以获得新的 c++17 版本,如果你能展示一个 std::for_each() 并行重载使用的小例子

标签: c++ multithreading


【解决方案1】:

您应该将向量划分为范围并在线程池线程中处理每个范围。

C++17 并行算法是实现这一目标的简单方法。使用std算法,不需要手动划分向量、调用线程池等操作。

您可以在不支持 C++17 的情况下使用 Intel TBB 库或 Open MP 指令来实现类似的功能。

或者推出你自己的实现。 std::async 是运行一个线程池任务,std::hardware_concurrency 是用来估计核数

并行示例for_each:

#include <algorithm>
#include <chrono>
#include <iostream>
#include <execution>
#include <mutex>
#include <string>
#include <thread>

using namespace std;

vector<string> vecFilenames1;
vector<string> vecFilenames2;

int main() {
    for (int i = 1; i < 1000; i++)
    {
        vecFilenames1.push_back("filename1_" + to_string(i));
        vecFilenames2.push_back("filename2_" + to_string(i));
    }

    mutex m;

    auto f = [&](const string& fn1)
    {
        // Comupute other element via pointer arthimetics
        // Works only with vector, for, say, deque, use container of struct
        const string& fn2 = vecFilenames2[&fn1 - vecFilenames1.data()];

        // simulate processing (to hide mutex unfairness and make threads
        // working concurrently)
        // replace with read processing
        using namespace chrono_literals;
        this_thread::sleep_for(30ms);

        // avoid doing any real work under the lock to benefit from paralleling
        lock_guard<mutex> guard(m);

        // ideally don't do console i/o from thread pool in real code
        cout << "Processing " << fn1 << " & " << fn2
            << " from " << this_thread::get_id() << '\n';
    };

    for_each(execution::par, vecFilenames1.begin(), vecFilenames1.end(), f);

    return 0;
}

【讨论】:

  • 您需要按照cppreference tables 的建议切换到 gcc 9。尽管 C++17 并行算法并不是唯一的方法。您可以使用英特尔 TBB 库或 Open MP 指令。
  • 其实gcc 9.1 gcc.gnu.org/onlinedocs/libstdc++/manual/…(找Parallelism TS)
  • 你能分享一些c++ 17并行std算法使用的例子吗?
  • 添加示例
  • 你检查你的代码了吗?我有一个错误error: 'mutex' was not declared in this scope。 (包括 并且没有任何变化)。PS 请参阅我关于 gcc 版本的 2 编辑
猜你喜欢
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
相关资源
最近更新 更多