【问题标题】:How do I create different number of threads in c++?如何在 C++ 中创建不同数量的线程?
【发布时间】:2020-04-07 08:51:31
【问题描述】:

在我的程序中,我想从用户那里获取线程数。例如,用户输入线程数为 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::thread 而不是 pthread_t 并且根本不使用指针。
  • 您的mythread-变量是您的for-loop 的本地变量,它不存在于它之外。
  • 您还有未定义的行为:对于i 的任何值> 0 mythread[i] 超出范围。

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


【解决方案1】:

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

我建议您执行以下操作:创建一个 std::threads 的 std::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
}

【讨论】:

  • @DikotaLolly 如果对您有帮助,请不要忘记投票并接受答案
猜你喜欢
  • 1970-01-01
  • 2021-11-24
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
相关资源
最近更新 更多