【问题标题】:Calling a function with different number of threads passed to the application调用具有传递给应用程序的不同线程数的函数
【发布时间】:2010-10-21 21:23:43
【问题描述】:

我有一个函数,每次都需要使用不同数量的线程调用(我正在做一些性能计算,所以需要知道性能何时开始恶化)。示例如下:

getTime() {
    return 0;
}

int main() {
    boost::threadpool::thread_pool<> threads(nThreads);

    for(int j = 0; j <= nLines; j++){
        threads.schedule(boost::bind(&getTime, nThreads, 1));
    }

    threads.wait();
}

在哪里, nThreads:在命令行中给出的值

我的问题是,这是否会给我想要的结果,至于每次程序访问 for 循环时是否会使用“nThreads”调用“getTime”函数?还是我需要其他方法来找出相同的?

我真正想做的是:

boost::threadpool::thread_pool<> threads(nThreads); 
// start a new thread that calls the "getTime" function 
for(int j = 0; j <= nLines; j++){ 
    //threads.schedule(boost::bind(&getTime, nThreads, 1));
    threads.schedule(boost::bind(&getTime, 0, nLines, pc)); 
}

(不确定以上哪个是正确的。)

getTime() 函数将以我从文本文件中获取的指定行数运行,并将每一行提供给我希望计算其性能的 api。但这与我的问题无关。

我希望每次调用具有不同线程数的函数并计算每个线程完成的时间。 1 个线程的总时间是多少,2 个线程完成的总时间是多少,等等。

【问题讨论】:

    标签: c++ multithreading boost-thread boost-bind


    【解决方案1】:

    如果我理解正确,你真正想做的是这样的:

    int main() 
    {
        int nbThreads = 20;
        boost::threadpool::thread_pool<> threads(nbThreads);
    
        for(int threadId = 0; threadId <= nbThreads ; ++threadId)
        {
            threads.schedule(getTime);
        }
        threads.wait();  
    }
    

    如果我是对的,你不需要在这里使用 boost::bind。

    请注意,Boost.ThreadPool 不是 Boost 的一部分(但是?它)。它将是reviewed,但尚未计划审核日期。

    【讨论】:

    • 对不起我的错。没有说明我想让进程针对多个不同的值运行,这些值存储在该行变量中并在 getTime() 中初始化。因此需要 FOR 循环。您给出的内容将意味着我给出的另一个 FOR 循环。如有错误请纠正我?
    • 对不起,我猜我还是没弄好。我所理解的是,您想做一些工作(我不知道具体是什么)并将其分配给提供的线程数。这项工作似乎是对 getTime 函数的 nbLines 调用,但我不确定。而且我不知道您想如何在所有这些中使用 nbLines。请尝试更精确!
    • 我已经编辑了主要问题。如果要求仍不清楚,请告知。
    • 您能否发布一些(几乎)工作代码,这些代码仅在一个线程中某些工作?那会更清楚...
    【解决方案2】:

    使用OpenMP 之类的东西怎么样?如果可扩展性是您的目标,那么它可能是更好的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-11
      • 2022-01-12
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多