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

问题描述 投票:1回答:1

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

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

c++ multithreading c++11 pthreads pthread-join
1个回答
1
投票

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

[我建议您执行以下操作:创建一个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
}
© www.soinside.com 2019 - 2024. All rights reserved.