首页 > 其他分享 >多线程执行函数(迭代器版本)

多线程执行函数(迭代器版本)

时间:2024-08-08 13:05:14浏览次数:8  
标签:std last 迭代 Iterator numThreads 版本 多线程 block first

#include <iostream>
#include <numeric>
#include <thread>
#include <vector>

template<typename Iterator, typename T>
struct threadBlock
{
    void operator()(T(*func)(Iterator, Iterator, T), Iterator first, Iterator last, T& result)
    {
        result = func(first, last, result);
    }
};
/**
 *
 * @tparam Iterator 迭代器类型
 * @tparam T 数据类型
 * @param func 执行函数
 * @param first 首个元素
 * @param last 最后一个元素
 * @param init 初始值
 * @param threadNum 线程数
 * @return
 */
template<typename Iterator, typename T>
T execInThread(T(*func)(Iterator, Iterator, T), Iterator first, Iterator last, T init, unsigned int threadNum = 0)
{
    auto length = std::distance(first, last);
    if (length == 0) return init;

    auto  numThreads = std::thread::hardware_concurrency();
    if (threadNum != 0 && threadNum < numThreads)
    {
        numThreads = threadNum;
    }
    if (numThreads == 0) numThreads = 1;

    std::vector<T> results(numThreads);
    Iterator block_start = first;

    if (numThreads > 1)
    {
        auto preThread = static_cast<int>(std::floor(static_cast<float>(length) / static_cast<float>(numThreads)));

        std::vector<std::thread> threads(numThreads - 1);

        for (unsigned long i = 0; i < (numThreads - 1); ++i)
        {
            Iterator block_end = block_start;
            std::advance(block_end, preThread);
            threads[i] = std::thread(threadBlock<Iterator, T>(), func, block_start, block_end, std::ref(results[i]));
            block_start = block_end;
        }
        for (auto& entry : threads)
        {
            entry.join();
        }

    }
    threadBlock<Iterator, T>()(func, block_start, last, results[numThreads - 1]);

    threadBlock<Iterator, T>()(func, results.begin(), results.end(), init);
    return init;
}

template<typename Iterator, typename T>
T testFunction(Iterator first, Iterator last, T init)
{
    T result(init);
    for (Iterator it = first; it < last; ++it)
    {
        result += *it;
    }
    return result;
}
int main()
{
    std::vector<int> nums(5000);
    for (int i = 0; i < 5000; ++i)
    {
        nums.at(i) = i;
    }

    //int result1 = execInThread(std::accumulate, nums.begin(), nums.end(), 0, 2);
    int result2 = execInThread(testFunction, nums.begin(), nums.end(), 0, 2);
    std::cout << result2 << '\n';
}

 

标签:std,last,迭代,Iterator,numThreads,版本,多线程,block,first
From: https://www.cnblogs.com/chanyuantiandao/p/18348717

相关文章

  • Flink 1.20 最新版本 Windows本地运行
    ApacheFlink1.20是Flink的一个较新版本,它带来了许多改进和新功能,如物化表、统一的检查点文件合并机制等。然而,关于Flink1.20在Windows本地运行的具体步骤,虽然Flink本身是跨平台的,但官方文档和社区资源可能更多地关注于Linux环境下的部署和配置。不过,基于Flin......
  • 无法使用 devstack 安装 openstack 因为 python 版本
    我正在使用默认的python3.8.10运行./stack.sh,我收到此错误,因为我需要3.9或更高版本3.8msg错误但是当我将默认版本更改为3.9时,我收到错误没有找到模块“apt_pkg”3.9msgerror我一直在em之间来回跳动,但错误仍然存​​在(我也每次都会检查版本)......
  • 如何迭代并将字典的所有值放入另一个具有不同键的字典列表中
    我正在尝试迭代字典列表并获取2个键的值,并将这些值写入另一个具有另一个键的字典列表。下面是我试图写入的输出列表。post_obj=[{"city":place["place"],"display":place["seq"]}]输入:data=[{'place':'SanJose',......
  • 【数值计算方法】线性方程组的迭代解法-数值实验
    fromformu_libimport*importnumpyasnpA=np.array([[-55,-5,12],[21,36,-13],[24,7,47]])b=np.array([41,52,12])w=lambdat:0.1*txs,ys,ts=[],[],[]foriinrange(1,20):_,err=SORIter(A,b,w(i))xs.append(list(......
  • 线性方程组迭代算法的Python实现
    更多精彩,关注博客园主页,不断学习!不断进步!我的主页csdn很少看私信,有事请b站私信博客园主页-发文字笔记-常用有限元鹰的主页内容:ABAQUS数值模拟相关Python科学计算开源框架,编程学习笔记哔哩哔哩主页-发视频-常用FE-有限元鹰的个人空间内容:模拟案例网格划分游戏视频,......
  • macos上安装esp-idf v4.2版本
    参考https://docs.espressif.com/projects/esp-idf/en/release-v5.0/esp32/get-started/linux-macos-setup.html安装Prerequisitesbrewinstallcmakeninjadfu-utilgit下载idf4.2版本并安装gitclone-brelease/v4.2--recursivehttps://github.com/espressif/esp-idf......
  • for 循环入门:迭代与应用
    1.引言    在之前我们讨论了while循环,while循环会在每次循环前进行检验,符合标准才会进行循环,这种循环是不定循环,有不定循环就会有定循环,现在让我们来讨论一下定循环2.for键    for键是定循环的关键字(keyword)让我们来看一下下面的代码foriin[5,4,3,2,1]......
  • 2.3.6版本发布!Apache SeaTunnel Zeta引擎迎来新架构!
    ApacheSeaTunnel2.3.6版本于近日正式发布,社区期待的SeaTunnelZetaMaster/Worker新架构、事件通知机制、支持动态编译的transform等新功能和新能力在这次版本中都有了全面的更新,并添加了首个向量数据库Milvus。此外,本版本还进行了一些基础性的Bug修复和文档修复等,欢迎尝......
  • 回滚Git版本
    在Git的版本控制中,我们经常会遇到需要回滚到之前的某个Commit的情况。回滚操作可以帮助我们撤销之前的更改,返回到某个稳定的状态。下面,我将介绍几种常见的Git回滚方法,并提供实际操作步骤和示例代码。一、软回滚(SoftReset)软回滚会保留你的更改,但是会取消这些更改的提交。换句......
  • uniapp Vue3版本使用jweixin-module报错
    把uniapp从Vue2版本选择到Vue3版本编译开发  改用到Vue3使用:varjweixin=require('jweixin-module')会编译报错:requireisnotdefined,没有require模块.改成import的话,由于jweixin-module不支持export写法,所以引入也不能成功1import *asjweixinfr......