【问题标题】:How to run each function from vector in new separate thread?如何在新的单独线程中从向量运行每个函数?
【发布时间】:2011-02-02 02:15:58
【问题描述】:

所以我有类似的东西

typedef boost::function<void(DataType)>   Function;
typedef std::vector<Function>      FunctionSequence;
typedef typename FunctionSequence::iterator FunctionIterator; 


DataType* dataElement;
FunctionSequence funcs; 
    //...
    for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it){
        DataType dataCopy;
        dataCopy = *dataElement;
        (*it)(dataCopy);

如何使用 boost.thread 使每个向量函数在单独的新线程中运行,或者如果它最好有一个线程向量而不是每次都创建 therad?

【问题讨论】:

  • 不确定您要完成什么。你能再详细一点吗?您是否尝试在同一个 DataType 实例上执行每个函数?如果是这样,这些函数会修改 DataType 的值吗?谢谢

标签: c++ multithreading boost boost-thread


【解决方案1】:

如果您尝试为每个函数启动一个新线程,并传入您的 DataType 对象的副本,您将需要使用 Boost Threads 和 Boost Bind:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

boost::thread_group tg;

for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it)
{
    tg.create_thread(boost::bind(*it, *dataElement));
}

tg.join_all();

首先,您创建一个boost::thread_group,它将作为您启动的所有线程的容器。然后create_thread 将启动一个新线程并调用传递给它的函数。在这种情况下,我们想要调用的不仅仅是一个简单的函数,所以我们需要使用boost::bind 创建一个线程可以运行的void() 函数。对boost::bind 的调用首先指定要调用的函数,然后指定要传递给函数的任何参数。它已经复制了参数,因此无需事先创建另一个副本。

启动所有线程后,您可以调用tg.join_all() 等待所有线程完成后再继续。调用join_all() 非常重要,可以确保线程不会在后台运行流氓。

显然,如果您有很多要调用的函数并且不希望创建那么多线程,则您必须跟踪未完成线程的数量,并且只有在现有线程退出后才创建新线程。这将需要在被调用的函数内进行一些额外的簿记(并且可能涉及包装函数)。您的情况可能不需要它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 2017-05-07
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2021-06-17
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多