我目前正在从事这个项目,我需要计算 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 个线程时,我得到错误的输出:
最佳答案
看来您的程序在使用两个线程时允许两个线程直接操作全局/共享资源“总和”,而无需任何同步保护。
换句话说,两个线程可以同时操作“sum”。任何时候“sum”的值都不会是预期的值(即:因为它只有一个线程)。
你的程序需要在两个线程之间实现某种访问同步;例如信号量、自旋锁、互斥锁、原子操作等。如果实现得当,这些功能将允许两个(或更多)线程共享单个任务(计算 PI)。
关于c - Windows 线程 API : Calculate PI value with multiple threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23165785/