在我的程序中,我想从用户那里获得线程数。例如,用户输入的线程数为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::vector
的std::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/