Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何通过std::thread生成多个线程?_C++_Multithreading_C++11_Threadpool - Fatal编程技术网

C++ 如何通过std::thread生成多个线程?

C++ 如何通过std::thread生成多个线程?,c++,multithreading,c++11,threadpool,C++,Multithreading,C++11,Threadpool,众所周知,我们可以通过std::threadt1(func)生成一个线程; 但是我们如何通过向量创建20个线程呢?一个示例解决方案是: std::vector<std::thread> my_threads{}; my_threads.reserve(20); for(int i = 0; i < 20; i++) my_threads.emplace_back([i]{ std::cout << "[" << i <&l

众所周知,我们可以通过std::threadt1(func)生成一个线程;
但是我们如何通过向量创建20个线程呢?

一个示例解决方案是:

std::vector<std::thread> my_threads{};
my_threads.reserve(20);

for(int i = 0; i < 20; i++)
    my_threads.emplace_back([i]{
        std::cout << "[" << i << "] Going to sleep\n";
        this_thread::sleep_for(std::chrono::seconds{1});
        std::cout << "[" << i << "] Hey I'm back :)\n";
    });

for(auto& thread : my_threads)
    if(thread.joinable())
        thread.join();
std::vector my_threads{};
我的线程保留(20);
对于(int i=0;i<20;i++)
我的线程。将线程放回([i]{

std::cout如果我做对了,你可以循环,每次迭代都创建新线程,将其添加到vector中,诸如此类,你是对的。我只是想我可以将指针推到vector中,然后像这样新建线程“threads_u.emplace_back(new std::thread(&ThreadPool::Process,this,I))”。谢谢。你不需要
If(thread.joinable())
conditional.“已完成代码执行但尚未加入的线程仍被视为活动执行线程,因此可以加入。”