所以我有一个结构如下:
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[]){
}
我尝试了各种方法,但总是收到错误消息,即我传入的内容不正确,我该如何正确执行此操作,以便我可以访问和处理我传入的每个结构对象中的变量?我有一种感觉,由于我使用了一个结构数组,我的语法在某处是错误的……我只是不知道哪里或什么地方错了。任何帮助将不胜感激!
最佳答案
void *threadFunction(void * threadP[]){
在 C++ 中,函数不能有数组类型的参数,参数必须是指针,用作函数参数的数组会衰减为指向第一个元素的指针,因此声明等同于:
void *threadFunction(void ** threadP){
这显然不是传递给 pthread_create
的正确类型
您需要传递具有此签名的函数:
void *threadFunction(void * threadP)
关于c++ - 将结构数组传递给 pthread_create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12984371/