2013-07-04 266 views
0

我正在通过传递他们的结构和运行到一些问题通过创建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; 

当我编译时,我得到一个错误信息“请求成员'ray'在'参数',它是非类类型'v *'”。

我是否会通过这种方式添加这个动态数组而导致错误的路径?

我很感激任何人都可以提供的帮助。

+0

在'argument.current = arr;',什么是'current'?一个错字? – johnchen902

+0

C++中不允许使用可变长度数组。 –

+0

除非有非常好的理由否则,只需使用'std :: vector ray;'。 –

回答

1

我明白动态数组不会在结构工作之前,在main()

在至极的方式应他们“不工作”,宣布?只要您定义并正确使用它们,就无需声明/定义它们。

int arr[i][j]; - 这是一个VLA,因为ij不是编译时常量。 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::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(); 
} 

没有线程内部摆弄,不需要手动内存管理。