c - Windows 线程 API : Calculate PI value with multiple threads

标签 c windows multithreading api

我目前正在从事这个项目,我需要计算 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 个线程时,我得到错误的输出:

Wrong PI value

最佳答案

看来您的程序在使用两个线程时允许两个线程直接操作全局/共享资源“总和”,而无需任何同步保护。

换句话说,两个线程可以同时操作“sum”。任何时候“sum”的值都不会是预期的值(即:因为它只有一个线程)。

你的程序需要在两个线程之间实现某种访问同步;例如信号量、自旋锁、互斥锁、原子操作等。如果实现得当,这些功能将允许两个(或更多)线程共享单个任务(计算 PI)。

关于c - Windows 线程 API : Calculate PI value with multiple threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23165785/

相关文章:

c - 使用命令行参数 fork

c - 语言 : C; Single scanf() for 1 or 2 inputs

c - 使用 Visual Studio 2010,如何向 Visual C++ Win32 控制台应用程序提供输入?

java - 安卓 native Activity 。如何在其他线程中做一些工作?

c++ - 互斥锁是否正常工作?不能死锁

objective-c - 将 "hello world"扩展为 HelloWorld 的 C 预处理器宏

c - 在 C 中,如何打印出一个字符数组然后清空它?

.net - 有什么方法可以让应用平台的中间代码独立?

c++ - 在可移植应用程序中使用 Windows DLL

java - Lucene:多线程文档复制