-3
请协助,我想创建5个线程来计算素数。我已经用下面的代码尝试了这种方式,但我被告知它不正确。多个线程创建5个线程来计算素数
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
pthread_mutex_t mutexprime;
请协助,我想创建5个线程来计算素数。我已经用下面的代码尝试了这种方式,但我被告知它不正确。多个线程创建5个线程来计算素数
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
pthread_mutex_t mutexprime;
在这里你有一个例子,如何使你想要的尽可能多的线程。希望能帮助到你。
int main() {
int num_threads;
cout << endl << "Enter number of threads: ";
cin >> num_threads;
vector<thread> t;
for (int i = 0;i <= num_threads;i++) {
t.push_back(thread(/*fucntion*/, ref(/*add here variable1*/), ref(/*here variable 2*/)));
}
for (auto &tt : t) { tt.join(); //Join the threads when finish
t.clear();//clean vector.
system("cls");
}
return 0;
}
不要忘了mutex
阻止你的变量我没有复制的所有代码: –
这还不是全部。你应该把你的问题扩展到[mcve]。 – zx485
您标记了C++,所以在这里你去:http://timmurphy.org/2010/05/04/pthreads-in-ca-minimal-working-example/ http://www.cplusplus.com/reference/thread/thread/https://theboostcpplibraries.com/boost.thread-management如果你在C++中编码,我建议第二个。 3种不同的方法 –