繁体   English   中英

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

[英]How do I create different number of threads in c++?

在我的程序中,我想从用户那里获取线程数。 例如,用户输入线程数为 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);

错误:在此 scope 中未声明“mythread”。

这段代码有什么问题? 你有更好的主意来创建用户定义的线程数吗?

首先,您在创建线程时有 memory 泄漏,因为您分配了 memory 但随后失去了对它的引用。

我建议您执行以下操作:创建std::threadstd::vector (因此,根本不要使用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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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