c++ - 如何在c++中创建不同数量的线程?

标签 c++ multithreading c++11 pthreads pthread-join

在我的程序中,我想从用户那里获得线程数。例如,用户输入的线程数为5,我想创建5个线程。仅在程序开始时才需要。在程序执行期间,我不需要更改线程数。因此,我编写了如下代码:

int numberOfThread;

cout << "Enter number of threads: " ;
cin >> numberOfThread;

for(int i = 0; i < numberOfThread; i++)
{
    pthread_t* mythread = new pthread_t;
    pthread_create(&mythread[i],NULL, myThreadFunction, NULL);
}

for(int i = 0; i < numberOfThread; i++)
{
    pthread_join(mythread[i], NULL);
}

return 0;

但是我在这一行中有一个错误 pthread_join(mythread [i],NULL);

错误:在此范围内未声明“mythread”。

该代码有什么问题?
您是否有更好的主意来创建用户定义的线程数?

最佳答案

首先,创建线程时会发生内存泄漏,因为您分配了内存,但随后却丢失了对其的引用。

我建议您执行以下操作:创建一个std::vectorstd::thread(因此,根本不要使用pthread_t),然后可以得到类似以下内容的内容:

std::vector<std::thread> threads;
for (std::size_t i = 0; i < numberOfThread; i++) {
    threads.emplace_back(myThreadFunction, 1);
}

for (auto& thread : threads) {
    thread.join();
}

如果您的myThreadFunction看起来像:

void myThreadFunction(int n) {
    std::cout << n << std::endl; // output: 1, from several different threads
}

关于c++ - 如何在c++中创建不同数量的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61076198/

相关文章:

c++ - 列表、命名空间中的嵌套名称说明符中的类型不完整

c++ - 构建 python 模块并将其与 MacOSX 框架链接

java - 如何从 SupplySync 返回对象而不阻塞主线程?

c++ - std future 异常 - 已检索,std bug?

C++ ffmpeg实时视频传输

multithreading - 何时使用非阻塞 >!/线程和阻塞>!!/带有 clojure core.async 的 goroutines

ios - 核心数据将数据插入数据库需要很长时间

c++ - 摆脱有符号和无符号整数表达式之间比较的优雅方法

c++ - 发布由指针管理的列表的添加和打印元素

c++ - 在 Visual Studio 解决方案中设置所有项目的运行时库