如何在C++中使用多线程

How do I use multithreading in C++?

本文关键字:多线程 C++      更新时间:2023-10-16

我需要知道如何从一个数字中制作未知数量的线程,这是我的代码:

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.
}

我真的想过制作一个数组,但我不能,因为我收到的数字对于函数来说是未知的,有什么方法可以在这个函数中乘以线程吗?

尝试在函数中使用std::vector

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

然后使用 push_back(thread t) 将线程添加到向量中,如下所示:myThreads.push_back(thread) ,但是如果这个问题对您来说很难,那么远离线程一段时间可能是个好主意,因为它们使程序非常复杂。