我有一个 C++ 程序,它使用 t 个线程对从 0 到 n 的数字求和。N 和 T 作为命令行参数传递。我正在使用创建 pthread 的 for 循环和将主线程重新加入它们的第二个 for 循环。当我使用少于 11 或 12 个线程时,程序运行良好。例如,在输入 100 10 时,它返回 5050。当我使用超过 11-12 个线程时,它会导致分段错误并崩溃。我似乎无法弄清楚为什么。我的代码中有一些行用于调试,例如打印到提示符等。感谢任何提示!
int n = 0;
int t = 0;
unsigned long gsum = 0;
pthread_mutex_t mutexsum;
void *sum(void *Index)
{
int index = (int)(int *) Index;
int threadSum = 0;
int k;
int lowerBound, upperBound; //used to find range of numbers to sum
//printf("I am here: %d \n",index);
if (index == t - 1) {
lowerBound = (n/t)*(t-1);
upperBound = n;
} else {
lowerBound = (n/t)*index;
upperBound = (n/t)*(index+1)-1;
}
for (k = lowerBound; k < upperBound + 1; k++) {
threadSum = threadSum + k;
}
// Critical Section
pthread_mutex_lock(&mutexsum);
gsum = gsum + threadSum;
pthread_mutex_unlock(&mutexsum);
pthread_exit((void*) 0);
}
int main(int argc, char* argv[]){
int i, k, j;
pthread_t sumThreads [t];
for(i = 1; i < argc; i++) {
if(i == 1)
n = atoi(argv[i]);
if(i == 2)
t = atoi(argv[i]);
}
if (n < 0 || t <= 0 || argc != 3) {
printf("Invalid or missing parameters! \n");
exit(0);
}
for (k = 0; k < t; k++) {
int nt = -1;
nt = pthread_create(&sumThreads[k], NULL, sum, (void*)k);
printf("%d \n", nt);
}
for (j = 0; j < t; j++) {
int rj = -1;
rj = pthread_join (sumThreads[j], NULL);
printf("%d \n", rj);
}
printf("Total Sum: %lu \n",gsum);
return 0;