中值积分定理计算PI值的多线程实现

// Parallel.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>

static long num_steps = 100000;
const int numThreads = 4;
double step, pi;

CRITICAL_SECTION g_cs;
double sum = 0.0;

DWORD WINAPI countFunc(LPVOID pArg) {
	double x;
	int i;
	int temp = *(int *)pArg;
	int start = (temp*num_steps) / 4;
	int end = start + num_steps / 4;
	for (i = start; i < end; i++) {
		EnterCriticalSection(&g_cs);
		x = (i + 0.5)*step;
		sum = sum + 4.0 / (1.0 + x*x);
		LeaveCriticalSection(&g_cs);
	}
	return 0;
}

void main()
{
	int i;
	HANDLE hThread[numThreads];
	step = 1.0 / (double)num_steps;
	int tNum[numThreads];

	InitializeCriticalSection(&g_cs);

	for (int i = 0; i < numThreads; i++) {
		tNum[i] = i;
		hThread[i] = CreateThread(NULL, 0, countFunc, (LPVOID)&tNum[i], 0, NULL);
	}

	WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE);
	DeleteCriticalSection(&g_cs);
	pi = step * sum;
	printf("PI = %12.9f\n", pi);
	system("pause");
}

你可能感兴趣的:(多线程)