【发布时间】:2019-05-18 17:13:40
【问题描述】:
我想在 c 中编写一个程序,该程序将使用 pthreads 对数组的平方数求和以实现代码的并行执行,但是在 linux 环境中执行代码时,我得到 分段错误(核心哑)消息。
奇怪的是,当我通过 DevC++ 在 windows 环境中运行完全相同的代码时,代码执行没有问题。
除此之外,似乎只有 1 个线程正在完成工作,导致串行执行。
我不知道我是否错了,但pthread_self() 返回的是相同的 ID。总的来说,我还是 pthreads 和编程的新手,我找不到问题所在,所以我需要你的帮助。
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <math.h>
void *calculation(int table[], int k);
pthread_mutex_t sum_mutex = PTHREAD_MUTEX_INITIALIZER;
int n, p, sum = 0;
int main()
{
int i, k=0, check, *table;
printf("Give the number of threads:\n");
scanf("%d",&p);
pthread_t threads[p];
printf("Give the number of elements of the table:");
do{
printf("The number of elements must be an integral multiple of the number of threads\n");
scanf("%d",&n);
check=n%p;
if(check!=0){
printf("Jesus how hard is it?\n");
printf("Try one more time\n");
printf("Give the number of elements of the table:\n");
}
}while(check!=0);
table = (int*) malloc(n * sizeof(int));
if(table == NULL){
printf("Error! Memory not allocated.\n");
exit(0);
}
printf("Give the elements of the table:\n");
for(i=0;i<n;i++){
scanf("%d",&table[i]);
}
for(i=0;i<p;i++){ //thread creation
pthread_create(&threads[i], NULL, calculation(table, k), NULL);
k++; //k is a variable used to seperate table, explained later
}
for(i=0;i<p;i++){
pthread_join(threads[i],NULL);
}
printf("Sum of vector= %d\n",sum);
free(table);
exit(0);
return 0;
}
void *calculation(int table[], int k){
int i;
int local_sum=0;
for(i=(n/p)*k;i<(n/p)*(k+1);i++) //this algorithm seperates the table into equivelant pieces and
{ //every pthread is calculating its given piece then stores that value in its local variable sum
if((n/p)>n){ //then it is updating the global variable
pthread_exit(NULL);
}
local_sum+=pow(table[i], 2);
printf("Thread's %lu calculation is %d\n", pthread_self(), local_sum);
}
pthread_mutex_lock(&sum_mutex); //mutex used here to protect the critical code
sum += local_sum;
pthread_mutex_unlock(&sum_mutex);
}
如果我没记错的话,一个线程正在运行代码的不同“副本”,因此每个线程的局部变量是不同的。在计算 local_sum 后,它会更新由于明显原因而受到保护的全局总和。
正如我所说,在 Windows 环境中,这段代码运行平稳,但似乎同一个 pthread 正在完成所有工作。相反,工作应该被分成尽可能多的线程。
不要忘记在 linux 环境中核心根本没有运行导致错误:分段错误(核心愚蠢)。
【问题讨论】:
-
关于:
pthread_create(&threads[i], NULL, calculation(table, k), NULL);函数名不能有参数