Create Threads in a loop

后端 未结 5 1295
难免孤独
难免孤独 2021-01-14 02:08

I just tested something like this:

boost::thread workerThread1(boost::bind(&Class::Function, this, ...);
boost::thread workerThread2(boost::bind(&Cla         


        
5条回答
  •  无人共我
    2021-01-14 02:47

    You can keep them in an array:

    size_t const thread_count = 5;
    boost::thread threads[thread_count];
    for (size_t i = 0; i < thread_count; ++i) {
        threads[i] = boost::bind(&Class::Function, this, ...));
    }
    

    In C++11, you can keep std::thread in friendlier containers such as std::vector:

    std::vector threads;
    for (int i = 0; i < 5; ++i) {
        threads.push_back(std::thread(boost::bind(&Class::Function, this, ...))));
    }
    

    This won't work with boost::thread in C++03, since boost::thread isn't copyable; the assignment from a temporary in my example works because of some Boost magic that sort-of emulates move semantics. I also couldn't get it to work with boost::thread in C++11, but that might be because I don't have the latest version of Boost. So in C++03, your stuck with either an array, or a container of (preferably smart) pointers.

提交回复
热议问题