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/

相关文章:

multithreading - 如何使用 Log4perl 在多线程 Perl 应用程序中轮换日志文件

c++ - 如何在重复循环中遍历 std::vector

c++ - 模板类成员特化声明

JavaScript Pi Spigot 算法不起作用

c++ - 当第二个线程从 map 中删除值时如何恢复线程?

c# - 使用哪个 C# 多线程选项

C++11线程编译错误,删除了拷贝构造函数和std::thread,为什么?

c++ - 抛出可由 C++98 和 C++1x 编译的析构函数。有没有更好的办法?

c++ - 在 C++ 中继续程序

c++ - 如何获取Windows中特定进程使用的物理内存和cpu?