我找到了一个简单的例子,它显示了如何treads
在C++
. 我了解它是如何工作的,但是我无法将源更改为使用vector
线程而不是array
. 我希望vector
能够创建尽可能多的线程。请有人告诉我,如何实现它以及我在哪里出错(注释代码是我试图实现的)?
#include <iostream>
#include <pthread.h>
#include <vector>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
int main ()
{
// vector<pthread_t> vectorOfThreads;
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
// rc = pthread_create(&vectorOfThreads[i], NULL,
// PrintHello, (void *)i);
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
return 1;
}
}
pthread_exit(NULL);
return 0;
}