【问题标题】:Windows Threading API: Calculate PI value with multiple threadsWindows 线程 API:使用多个线程计算 PI 值
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您需要使用互斥锁来访问由多个线程共享的数据,或者将数据保留在特定线程的本地,然后在所有线程完成后整理答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-20
      • 2015-06-19
      • 2015-08-30
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 2020-09-09
      • 2013-05-31
      相关资源
      最近更新 更多