gpt4 book ai didi

c - pthread并发运行线程c

转载 作者:行者123 更新时间:2023-12-01 12:45:55 25 4
gpt4 key购买 nike

我需要在c中用pthread制作Leibniz算法,现在我有这个代码,但目前线程实现需要与顺序实现相同的时间,我认为它不是并发运行的。有人可以看到错误。

谢谢!!

#include<stdio.h>
#include<math.h>
#include<pthread.h>
#include<stdlib.h>
#define NUM_THREADS 2
#define ITERATIONS 100000000
double result = 0.0;
void *leibniz(void *threadid){
int size = ITERATIONS/NUM_THREADS;
int start = (long)threadid * size;
int end = ((long)threadid+1) * size;
int i;
for(i = start; i<end; i++){
int denom = 2*i+1;
result += pow(-1.0, i) * (1.0/denom);
}
}

int main(){
pthread_t threads[NUM_THREADS];
long t;
int rc;

// CREATE
for(t=0;t<NUM_THREADS;t++){
rc = pthread_create(&threads[t], NULL, leibniz, (void *)t);
if(rc){
printf("ERROR: return code %d\n", rc);
}
}
// JOIN
for(t=0;t<NUM_THREADS;t++){
rc = pthread_join(threads[t], NULL);
if(rc){
printf("ERROR: return code %d\n", rc);
exit(-1);
}
}
printf("Pi %f\n", result*4);
exit(0);

}

感谢 Jean-François Fabre 我做了这些改变,现在它起作用了!
double result=0.0;

void *leibniz(void *threadid){
double local = 0.0;
int size = ITERATIONS/NUM_THREADS;
int start = (long)threadid * size;
int end = ((long)threadid+1) * size;
int i;
for(i = start; i<end; i++){
local += (i%2==0 ? 1 : -1) * (1.0/(2*i+1));
}
result += local*4;
}

最佳答案

我会尝试回答。

即使您的应用程序是多线程的,也不能保证每个内核有 1 个 FPU。我对此知之甚少,但我认为某些 AMD 处理器实际上在内核之间共享 FPU。

由于您的循环基本上是添加和 pow ,它是 99% 的 FPU 计算,所以如果 FPU 在您的计算机上共享,它解释了瓶颈。

您可以通过不调用 pow 来减少 FPU 的使用。只是为了计算 -11 ,这将是一个标量操作,然后可能会有所作为。只需使用 -1如果 i很奇怪,1否则,或在每次迭代时否定外部 1/-1 变量。

另外,为了避免竞争条件,将结果累积在本地结果中,并在最后添加(最后通过互斥锁保护添加会更好)

double result = 0.0;
void *leibniz(void *threadid){
double local = 0.0;
int size = ITERATIONS/NUM_THREADS;
int start = (long)threadid * size;
int end = ((long)threadid+1) * size;
int i;
for(i = start; i<end; i++){
int denom = 2*i+1;
// using a ternary/scalar speeds up the "pow" computation, multithread or not
local += (i%2 ? -1 : 1) * (1.0/denom);
}
// you may want to protect that addition with a pthread_mutex
// start of critical section
result += local;
// end of critical section
}

http://wccftech.com/amd-one-fpu-per-core-design-zen-processors/

关于c - pthread并发运行线程c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42705299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com