【问题标题】:Error when creating dynamic pthread_t创建动态 pthread_t 时出错
【发布时间】:2015-01-07 08:42:34
【问题描述】:

我正在尝试动态创建 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 ‘&amp;’ operand

【问题讨论】:

  • 您可能想选择一种语言。如果你选择 C++,你可以使用std::thread,这样会容易很多。

标签: c++ c multithreading memory-address


【解决方案1】:

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

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

还要注意演员 (void *)t 不正确。您应该传递一个指向有效对象的指针。

【讨论】:

    猜你喜欢
    • 2013-01-13
    • 2020-01-22
    • 2022-01-05
    • 2021-06-08
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 2013-07-31
    相关资源
    最近更新 更多