I'm new to threads.. I'm trying to write a function that would write the pid of the thread to a given vector. When I check the size of the vector at the end of the program, I expect it to be 2, instead of 1.
What is a suggested way to add data to the tmp
vector such that tmp
is not local to each thread?
#include <iostream>
#include <pthread.h>
#include <vector>
using namespace std;
#define NUM_THREADS 2
vector<pthread_t> tmp;
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
pthread_t pid = pthread_self();
tmp.push_back(pid);
cout << "Hello World! Thread ID, " << tid << " " << pid << endl;
pthread_exit(NULL);
}
int main ()
{
int rc;
int i;
vector<pthread_t> vectorOfThreads(NUM_THREADS);
for( i=0; i < NUM_THREADS; i++ ){
rc = pthread_create(&vectorOfThreads[i], NULL,
PrintHello, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
return 1;
}
}
cout << "size of tmp " << tmp.size() << endl;
pthread_exit(NULL);
return 0;
}