【发布时间】:2014-04-19 04:22:59
【问题描述】:
我目前正在做这个项目,我需要计算 PI 的值...
当只指定一个线程完美运行时,我得到 3.1416[...] 但是当我指定在 2 个或更多线程中解决进程时,我停止得到 3.1416 值,这是我的代码:
#include <stdio.h>
#include <time.h>
#include <windows.h>
//const int numThreads = 1;
//long long num_steps = 100000000;
const int numThreads = 2;
long long num_steps = 50000000;
double x, step, pi, sum = 0.0;
int i;
DWORD WINAPI ValueFunc(LPVOID arg){
for (i=0; i<=num_steps; i++) {
x = (i + .5)*step;
sum = sum + 4.0 / (1. + x*x);
}
printf("this is %d step\n", i);
return 0;
}
int main(int argc, char* argv[]) {
int count;
clock_t start, stop;
step = 1. / (double)num_steps;
start = clock();
HANDLE hThread[numThreads];
for ( count = 0; count < numThreads; count++) {
printf("This is thread %d\n", count);
hThread[count] = CreateThread(NULL, 0, ValueFunc, NULL, 0, NULL);
}
WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE);
pi = sum*step;
stop = clock();
printf("The value of PI is %15.12f\n", pi);
printf("The time to calculate PI was %f seconds\n", ((double)(stop - start) / 1000.0));
}
我在指定 2 个线程时得到了错误的输出:
【问题讨论】:
-
在这种特殊情况下,不需要同步对象:只需让每个线程分别将其自己的部分相加,然后在最后对每个线程的值求和。
标签: c windows multithreading api