我正在做一项作业,我必须使用 pthreads
C 处理一些图像。
我有以下结构:
typedef struct {
int type;
int width;
int height;
int max_value;
int *input;
}image;
和
typedef struct {
int id; // thread id
image *in; //input image
}ptf_arguments;
我还有一个函数,我尝试实例化一个struct_b数组,并将给定struct_a的参数分配给每个函数
void resize(image *in, image * out) {
int i;
pthread_t tid[num_threads];
ptf_arguments *arguments[num_threads];
arguments[0]->in->input = (int *)malloc(in->width * in->height * sizeof(int));
arguments[0]->in = in; // HERE
printf("First thread should have id = %d. In image of (%d)\n", arguments[0]->id, arguments[0]->in->width); //here
for(i = 0 ; i < num_threads; i++) {
pthread_create(&(tid[i]), NULL, resize_thread_function, &(arguments[i]));
}
}
1)我不太了解结构,我需要有人向我解释如何将输入/输出图像传递给我的 ptf_arguments 结构,以便我可以将其传递给 pthreads 函数。
2)我需要为图像结构分配内存吗?
3) 我是否需要为 ptf_arguments 结构的图像结构内的 int
数组分配内存?
谢谢
最佳答案
当我阅读代码时,我明白了
ptf_arguments *arguments[num_threads];
arguments[0]->in->undefined behavior
在取消引用之前,您需要将in
指向有效的image
结构。最简单的方法可能是将标记为 //HERE
的行移到上一行上方。
是的,您还需要分配一个int
数组,并将image
结构的input
成员指向该内存。不用说,您需要为每个 ptf_arguments 对象(而不仅仅是第一个对象)进行初始化和分配。
我认为传递单个 ptf_arguments
对象的地址的语法很好。
关于c 结构体和 pthread 指针分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53065952/