简体   繁体   中英

How do I use multithreading in C++?

I need to know how can I make an unknown number of threads from a number, here is my code:

void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N){
  ofstream file;
  file.open(filePath);
  thread myThreads[N];//cant make it because N isnt a constant value.
}

I really thought about making an array but I can't because the number I receive is unknown for the function, is there any way to multiply threads in this function?

Try using a std::vector in your function:

void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N){
  ofstream file;
  file.open(filePath);
  vector<std::thread> myThreads;
}

Then add the threads to the vector using push_back(thread t) , like this: myThreads.push_back(thread) , however if this question is difficult to you it might be a good idea to stay away from threads for a while, as they complicate a program very much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM