// 2.1.2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <Windows.h>
#define nmax 10000
int sum;
int t[nmax];
#define threadCount 4
//Critical section
CRITICAL_SECTION cs;
DWORD WINAPI ThreadFunc(LPVOID lpdwParam) {
int tid = (int)lpdwParam;
int s = 0;
int i;
int dn = nmax / threadCount;
int start = tid * dn;
int stop = tid != threadCount - 1 ? (tid + 1)*dn : nmax;
for (i = start; i<stop; i++) s += t[i];
// Get into critical section
EnterCriticalSection(&cs);
sum += s;
// Leave critical section
LeaveCriticalSection(&cs);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwThreadId, dwThrdParam[threadCount];
HANDLE ahThreads[threadCount];
InitializeCriticalSection(&cs);
int i, s = 0, z = 100;
for (i = 0; i<nmax; i++) t[i] = rand() % z;
//sequential
s = 0;
int time = GetTickCount();
for (i = 0; i<nmax; i++) s += t[i];
std::cout << "Sequential sum: " << s << std::endl;
time = time - GetTickCount();
std::cout << "Sequential sum time: " << s/10000 << " ticks of clock [*10000]" << std::endl;
//parallel
sum = 0;
time = GetTickCount();
for (i = 0; i<threadCount; i++)
{
dwThrdParam[i] = i;
ahThreads[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)dwThrdParam[i], 0, &dwThreadId);
}
for (i = 0; i<threadCount; i++)
{
WaitForMultipleObjects(threadCount, ahThreads, true, INFINITE);
}
time = time - GetTickCount();
std::cout << std::endl;
std::cout << "Parallel sum: " << sum << std::endl;
std::cout << "Parallel sum time: " << s / 10000 << " ticks of clock [*10000]" << std::endl;
DeleteCriticalSection(&cs);
std::cin.ignore(2);
return 0;
}
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}