C++thread并行笔记

用C++并行库thread去实现并行举例:

#include 
#include 
#include 

void copySmallVectorsToBigVector(const std::vector<std::vector<int>>& smallVectors,
                                 std::vector<int>& bigVector,
                                 size_t startIndex, size_t endIndex) {
    for (size_t i = startIndex; i < endIndex; ++i) {
        const std::vector<int>& smallVec = smallVectors[i];
        bigVector.insert(bigVector.end(), smallVec.begin(), smallVec.end());
    }
}

int main() {
    std::vector<std::vector<int>> smallVectors = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    std::vector<int> bigVector;
    size_t totalSize = 0;

    for (const std::vector<int>& smallVec : smallVectors) {
        totalSize += smallVec.size();
    }

    bigVector.reserve(totalSize);  // 预分配足够的内存

    const size_t numThreads = std::thread::hardware_concurrency();
    std::vector<std::thread> threads;

    for (size_t i = 0; i < numThreads; ++i) {
        size_t startIndex = i * (smallVectors.size() / numThreads);
        size_t endIndex = (i + 1) * (smallVectors.size() / numThreads);

        if (i == numThreads - 1) {
            endIndex = smallVectors.size();
        }

        threads.emplace_back(copySmallVectorsToBigVector,
                             std::ref(smallVectors), std::ref(bigVector), startIndex, endIndex);
    }

    for (std::thread& t : threads) {
        t.join();
    }

    // 显示结果
    for (int num : bigVector) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

注意:这是外层并行,外层的循环越多速度加快的越明显。

你可能感兴趣的:(工程技术,c++,thread,并行)