创建动态pthread_t时出错

时间:2015-01-07 08:42:34

标签: c++ c multithreading memory-address

我正在尝试动态创建pthread并面对变量的寻址问题。你能说出应该如何访问地址

int main (int argc, char *argv[])
{
   pthread_t *threads;
   int rc, numberOfThreads;
   long t;
   cout<<"Number of Threads = ";
   cin>>numberOfThreads;
   cout<<endl;
   threads =(pthread_t*) malloc(numberOfThreads*sizeof(pthread_t));
   for(t=0; t<numberOfThreads; t++){
      printf("In main: creating thread %ld\n", t);
     // **ERROR ON BELOW LINE**
      rc = pthread_create((pthread_t)&(threads+numberOfThreads), NULL, FunctionForThread, (void *)t);
      (void) pthread_join(threads[t], NULL);

      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }

   /* Last thing that main() should do */
   pthread_exit(NULL);
}

错误lvalue required as unary ‘&’ operand

1 个答案:

答案 0 :(得分:4)

pthread_create()需要pthread_t*类型作为第一个参数。你有一个pthread_t数组,所以传递其中一个的地址:

rc = pthread_create(&threads[i], NULL, FunctionForThread, (void *)t);

另请注意,投射(void *)t不正确。您应该将指针传递给有效对象。