【发布时间】:2017-04-23 15:32:24
【问题描述】:
我正在做一些需要使用 pthread 的事情。基本上,我想在矩阵上找到最大值,但我没有做所有的单处理工作,而是使用pthreads 来打破它。
我使用如下定义的一个结构向findMaxPerArea 函数输入多个值。当我在最后一行调用pthread_create(...); 时,问题就出现了。 printf 在它通过之前就好了。
请不要对我太苛刻,因为我知道这一定是一个愚蠢的错误。有什么想法吗?
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]);
}}
【问题讨论】:
-
使用您向我们展示的当前代码 sn-p,很难对您的代码进行推理。请将您的问题扩展到minimal, complete and verifiable example。
-
我更新了我的答案,这是我的全部代码。
-
不要使用演员表。就是这么简单。 (不,实际上没那么简单。有时你必须这样做。但作为第一个近似值,这条规则是有效的。你可以花费数年时间做 C 而不编写一个演员表。当你最终需要一个时,希望你有足够的经验去做对。)