Pthread将数据推送到全局向量

时间:2019-04-15 09:59:05

标签: c++ pthreads

我是线程的新手。我正在尝试编写一个函数,该函数会将线程的pid写入给定的向量。当我在程序结尾检查向量的大小时,我希望它是2,而不是1。

将数据添加到tmp向量以使tmp不是每个线程本地的建议方法是什么?

#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;
}

0 个答案:

没有答案