c++ - 通过结构将动态数组传递给 pthreads

标签 c++ arrays struct pthreads

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

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 of non-class type 'v*'”。

我以这种方式添加动态数组是否走错了路?

我感谢任何人可以提供的任何帮助。

最佳答案

I understand that dynamic arrays do not work in structs declared before the main()

它们应该以何种方式“不起作用”?只要您正确定义和使用它们,在何处声明/定义它们并不重要。

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

argument.current = arr;

I changed the struct to:

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

该结构中的 current 在哪里?难怪它无法编译 ;-)(您可能希望下次提供 SSCCE)。

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

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

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

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

并且由于您使用的是 C++,您很可能正在使用 C++11 或 boost,因此您很有可能 std::threadboost::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();
}

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

关于c++ - 通过结构将动态数组传递给 pthreads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462736/

相关文章:

c++ - 最后 5 个元素的读取访问权限

c++ - 在不编辑标题的情况下取消命名空间类的全局化

c++ - 有条件地替换字符串中的正则表达式匹配

javascript - 这是有效的 JavaScript 数组比较算法吗?

c++ - 在 copy-and-swap 习语中实现交换

javascript - 查找数组中数组元素的索引

C、在结构体中设置变量

C:使用大量结构会使程序变慢吗?

python - 如何在 Python 3 中交换两对字节

java - 寻找一种有效的方法来对 3D 数组的周围值求和