Y
Y
Yuriy2015-09-17 23:06:27
C++ / C#
Yuriy, 2015-09-17 23:06:27

How to dynamically create nth number of threads in c++ std::thread?

Initially, I don't know how many threads to create. How to get around this or is there a solution to create threads dynamically?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ruchkin, 2015-09-17
@Rivares1853

#include "stdafx.h"
#include <thread>
#include <vector>
#include <iostream>

void foo(std::size_t i)
{
  // nothing to do
}

int main()
{
  std::vector<std::thread> ths;
  std::size_t n;
  std::cin >> n;
  for (std::size_t i = 0; i < n; ++i)
    ths.push_back(std::thread(&foo, i));
  for (auto & th : ths)
    th.join();
  return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question