调用pthread_create并传递结构时出现分段错误
我正在做一些需要pthread使用的事情。基本上,我想在一个矩阵上找到最大值,但我不是单处理所有的工作,而是使用pthreads来打破它。 我使用一个结构(如下所述)向findMaxPerArea函数输入多个值。当我调用pthread_create…,问题就出现了。。。;在最后一行。在它通过之前的打印很好。 请不要对我太苛刻,因为我知道这一定是个愚蠢的错误。有什么想法吗调用pthread_create并传递结构时出现分段错误,c,pthreads,C,Pthreads,我正在做一些需要pthread使用的事情。基本上,我想在一个矩阵上找到最大值,但我不是单处理所有的工作,而是使用pthreads来打破它。 我使用一个结构(如下所述)向findMaxPerArea函数输入多个值。当我调用pthread_create…,问题就出现了。。。;在最后一行。在它通过之前的打印很好。 请不要对我太苛刻,因为我知道这一定是个愚蠢的错误。有什么想法吗 struct inputData{ int ** array; int start, stop, cols, thre
struct inputData{
int ** array;
int start, stop, cols, threadID;
int* localmax;
};
void* findMaxPerArea(void* tmp){
struct inputData* inp = (struct inputData*) tmp;
inp->localmax[inp->threadID] = 0;
int i, j;
for(i = inp->start; i < inp->stop; i++){
for(j = 0; j < inp->cols; j++){
if(inp->array[i][j] > inp->localmax[inp->threadID]) inp->localmax[inp->threadID] = inp->array[i][j];
}
}
}
int main(){
int N, p;
printf("Give me the number of threads\n");
scanf("%d", &p);
printf("Give me the number of rows and columns (one value)\n");
scanf("%d", &N);
int* localmax = malloc(p * sizeof(int));
pthread_t* threadArr = (pthread_t*) malloc(p*sizeof(pthread_t));
int** a = malloc(N * sizeof(int*));
for (int i = 0; i < N; i++) {
a[i] = malloc(N * sizeof(int));
}
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
a[i][j] = 5;
}
}
a[0][1] = 8;
a[1][1] = 13;
struct inputData* inputArray = (struct inputData*) malloc(p * sizeof(struct inputData));
for(int i = 0; i < p; i++){
inputArray[i].array = a;
inputArray[i].start = i*(N/p);
inputArray[i].stop = (N/p)*(i+1) - 1;
inputArray[i].cols = N;
inputArray[i].threadID = i;
inputArray[i].localmax = localmax;
printf("It passes this\n");
pthread_create((pthread_t*)threadArr[i], NULL, findMaxPerArea, (void*)&inputArray[i]);
}}
将threadArr[i]强制转换为pthread_t*没有意义,因为您将值强制转换为指针。相反,您希望完全省略强制转换,因为您已经在处理pthread_ts数组,并获取第i个元素的地址:
&threadArr[i]
根据您向我们展示的当前代码片段,很难对您的代码进行推理。请将您的问题扩展到功能a。我更新了我的答案,这是我的全部代码。不要使用强制转换。就这么简单。不,其实没那么简单。有时候你不得不这么做。但是作为第一近似,这个规则是有效的。你可以花很多年的时间来写C而不需要写一个演员。当您最终需要时,希望您有足够的经验来做正确的事情。@GusAndrianos不客气,但请不要在StackOverflow上使用任何脏话,它一点也不受欢迎,可能会删除您的问题和答案。对不起,我搜索了将近一个小时。
&threadArr[i]