在下面的程序中,增加线程数根本不会产生任何加速好处(用 linux 下的 time 命令测量)。我已经在以下处理器上运行它:
- 英特尔 i5 M520
- 英特尔至强 X5650
在我看来,在线程之间划分工作的逻辑是正确的。我什至尝试过移除锁,这显然给出了错误的结果,但速度仍然没有提高。有任何想法吗?
#include <pthread.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double sum;
pthread_mutex_t mutex;
typedef struct {
int start;
int end;
}sumArg;
void *sumRoots(void *arg) {
sumArg s = *((sumArg *) arg);
int i = s.start;
double tmp;
while(i <= s.end) {
tmp = sqrt(i);
pthread_mutex_lock(&mutex);
sum += tmp;
pthread_mutex_unlock(&mutex);
i++;
}
free(arg);
}
int main(int argc, char const *argv[]) {
int threadCount = atoi(argv[1]);
int N = atoi(argv[2]);
if (N < 1 || threadCount < 1) printf("Usage: ./sumOfRoots threads N\n");
pthread_t tid[threadCount];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&mutex, NULL);
sumArg *s;
int i = 0;
while(i < threadCount) {
s = (sumArg *) malloc(sizeof(sumArg));
s->start = ((N/threadCount) * i) + 1;
s->end = (N/threadCount) * (i + 1);
pthread_create(&tid[i], &attr, sumRoots, s);
i++;
}
i = 0;
while(i < threadCount) pthread_join(tid[i++], NULL);
printf("sum: %f\n", sum);
return 0;
}
编辑:这是程序的一些运行,全部在 i5 M520 上运行:
time ./sumOfRoots 1 1000000000
sum: 21081851083600.558594
real 0m21.933s
user 0m21.268s
sys 0m0.000s
time ./sumOfRoots 2 1000000000
sum: 21081851083600.691406
real 0m21.207s
user 0m21.020s
sys 0m0.008s
time ./sumOfRoots 4 1000000000
sum: 21081851083600.863281
real 0m21.488s
user 0m21.116s
sys 0m0.016s
time ./sumOfRoots 8 1000000000
sum: 21081851083601.777344
real 0m21.432s
user 0m21.092s
sys 0m0.020s
我相信总和的变化是由浮点精度损失引起的。