2013-10-30 66 views

回答

6

您可以简单地在循环中创建线程,每次传递不同的参数。在此示例中,它们存储在vector中,以便稍后可以加入它们。

struct Foo {}; 

void bar(const Foo& f) { .... }; 

int main() 
{ 
    std::vector<std::thread> threads; 
    for (int i = 0; i < 10; ++i) 
    threads.push_back(std::thread(bar, Foo())); 

    // do some other stuff 

    // loop again to join the threads 
    for (auto& t : threads) 
    t.join(); 
} 
0

做一个循环,每次迭代构造一个单独的线程对象,所有的函数都具有相同的功能,但不同的对象作为参数。

0

如果你想使用一些C++ 11的东西,以及利用性病的大国::功能+的std ::绑定你可以尝试这样的事:

#include <thread> 
#include <functional> 
#include <iostream> 
#include <vector> 
#include <memory> 

typedef std::function<void()> RunningFunction; 

class MyRunner 
{ 
private: 
    MyRunner(const MyRunner&); 
    MyRunner& operator=(const MyRunner&); 
    std::vector<std::thread> _threads; 

public: 

    MyRunner(uint32_t count, RunningFunction fn) : _threads() 
    { 
     _threads.reserve(count); 
     for (uint32_t i = 0; i < count; ++i) 
      _threads.emplace_back(fn); 
    } 

    void Join() 
    { 
     for (std::thread& t : _threads) 
      if (t.joinable()) 
       t.join(); 
    } 
}; 

typedef std::shared_ptr<MyRunner> MyRunnerPtr; 

class Foo 
{ 
public: 
    void Bar(uint32_t arg) 
    { 
     std::cout << std::this_thread::get_id() << " arg = " << arg << std::endl; 
    } 
}; 


int calcArg() 
{ 
    return rand() % UINT32_MAX; 
} 

int main(int argc, char** argv) 
{ 
    std::vector<Foo> objs; 

    for (uint32_t i = 0; i < 32; ++i) 
     objs.emplace_back(Foo()); 

    std::vector<MyRunnerPtr> runners; 

    for (Foo& obj : objs) 
    { 
     const uint32_t someArg = calcArg(); 
     runners.emplace_back(std::make_shared<MyRunner>(1, std::bind(&Foo::Bar, &obj, someArg))); 
    } 

    for (MyRunnerPtr& runner : runners) 
     runner->Join(); 
} 
相关问题