【问题标题】:Passing an array of structs to a pthread_create将结构数组传递给 pthread_create
【发布时间】:2012-10-20 01:05:58
【问题描述】:

所以我有一个结构如下:

struct threadData{
    string filename
    int one;
    int two;
};

我创建了一个这样的结构数组:

pthread_t threadID[5];
struct threadData *threadP;
threadP = new struct threadData[5];

然后我将这个结构数组传递给线程函数,如下所示:

for(int i = 0; i < 5; i++){
    pthread_create(&threadID[i], NULL, threadFunction, (void * ) threadP[i]);
}

这就是我的 threadFunction 的编写方式:

void *threadFunction(void * threadP[]){

}

我尝试了各种方法,但总是收到我传入的内容不正确的错误,我该如何正确执行此操作,以便我可以访问和处理我传入的每个结构对象中的变量?我有一种感觉,由于我使用了结构数组,我的语法在某处是错误的……我只是不知道哪里或什么地方出了问题。任何帮助将不胜感激!

【问题讨论】:

  • 应该是&amp;threadP[i]。就是这样。
  • 为什么不使用 std::thread?
  • 看起来你的函数应该声明为void *threadFunction(void * threadP),调用应该是pthread_create(&amp;threadID[i], NULL, threadFunction, (void * ) &amp;threadP[i]);

标签: c++ arrays pointers struct pthreads


【解决方案1】:
void *threadFunction(void * threadP[]){

函数在C++中不能有数组类型的参数,而参数必须是一个指针,并且用作函数参数的数组衰减为指向第一个元素的指针,因此声明等价于:

void *threadFunction(void ** threadP){

这显然不是传递给pthread_create的正确类型

你需要传递一个带有这个签名的函数:

void *threadFunction(void * threadP)

【讨论】:

  • 看起来你的大部分抱怨都是文体问题。你暗示了真正的问题,但不要解释太多。说不能将数组传递给 C++ 中的函数也有点误导。您可以,但是正如您所指出的,它们“衰减”为指针。但是,在某些情况下实际上需要数组语法——例如传递多维数组时。
  • 例如:eskimo.com/~scs/cclass/int/sx9a.html ...无论如何,多维数组与这种情况无关。但是,我只是想指出,您的说法有点误导。
  • 需要多解释吗?该函数是错误的类型,这就是它无法编译的原因。当你有一个多维数组时,你仍然没有数组类型的参数,你有一个指向数组的指针。我已经删除了文体 cmets 并改写了答案
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2011-07-21
  • 2016-01-07
相关资源
最近更新 更多