【问题标题】:Passing a dynamic array to pthreads via a struct通过结构将动态数组传递给 pthread
【发布时间】:2013-07-04 05:49:57
【问题描述】:

我正在通过将结构传递给 pthread 并遇到一些问题来创建 pthread。使用以下代码,我可以将一组整数放入结构中,然后在线程中使用它们:

struct v{
    int i;
    int j;
};
void* update(void* param);

int main(int argc, char* argv[]){
    ...
    int j = 2;
    int i = 1;
    pthread_t tid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct v *argument = (struct v*)malloc(sizeof(struct v));
    argument->i = i;
    argument->j = j;
    pthread_create(&tid, &attr, update, argument);
    ...
    pthread_join(tid, NULL);
    return 0;
}
void* update(void* arg){
    ...
    struct v * argument = (struct v*) arg;
    int j = argument->j;
    int i = argument->i;
    cout << j << ' ' << i << endl;
}

不幸的是,我似乎无法将动态数组添加到结构中。我知道动态数组在 main() 之前声明的结构中不起作用,但即使使用指针,我似乎也无法编译代码。在 main() 中,我添加了以下几行:

int arr[i][j];

下面

argument->j = j;

我补充说:

argument.current = arr;

我将结构更改为:

struct v{
    int i;
    int j;
    int *ray;
};

在更新功能中,我有:

int * curr = argument->ray;

当我编译时,我收到一条错误消息“request for member 'ray' in 'argument', which is non-class type 'v*'”。

这样添加这个动态数组是不是走错路了?

感谢任何人提供的任何帮助。

【问题讨论】:

  • 在argument.current = arr; 中,current 是什么?错字?
  • C++ 中不允许使用可变长度数组。
  • 除非有很好的理由不这样做,否则请使用std::vector&lt;int&gt; ray;。

标签: c++ arrays struct pthreads


【解决方案1】:

我了解动态数组在 main() 之前声明的结构中不起作用

他们应该以哪种方式“不工作”?只要您正确定义和使用它们,您在哪里声明/定义它们都没有关系。

int arr[i][j]; - 这是一个 VLA,因为 i 和 j 不是编译时常量。 VLA 不是 C++03 和 C++11 的一部分,它们是 C 特性。 C++14 将引入类似的东西。

argument.current = arr;

我将结构更改为:

 struct v{
     int i;
     int j;
     int *ray;
 };

current 在该结构中的什么位置?难怪它是否无法编译 ;-)(下次您可能需要提供 SSCCE)。

够吹毛求疵了,让我们试着解决你的问题:

二维数组不能用简单的指针来实现。您可以改用指向指针的指针,例如像这样:

struct v{
  int i;
  int j;
  int **ray;
};

但是由于您使用的是 C++,我建议您使用向量的向量或类似的东西。您可以在This SO answer找到更多关于二维数组分配的信息。

而且由于您使用的是 C++,因此您很可能正在使用 C++11 或 boost,因此您很有可能使用 std::thread 或 boost::thread,这是一个很好用的便携式包装器您的环境的线程,在您的情况下为 pThread。您的代码可能如下所示:

void update(std::vector<std::vector<int>>& param) { //or whatever signature suits your needs
  //...
}

int main() {
  int i = 42;
  int j = 11;
  std::vector<std::vector<int>> myVecVec(j, std::vector<int>(j));

  std::thread theThread( [&](){update(myVecVec);} );
  //or: 
  //std::thread theThread( update, std::ref(myVecVec) );

  //...

  theThread.join();
}

无需摆弄线程内部结构,无需手动内存管理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多