Facebook
From Filip Wicha, 5 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 274
  1. // 2.1.2.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <stdlib.h>
  7. #include <Windows.h>
  8.  
  9. #define nmax 10000
  10.  
  11. int sum;
  12. int t[nmax];
  13. #define threadCount 4
  14. //Critical section
  15. CRITICAL_SECTION cs;
  16.  
  17. DWORD WINAPI ThreadFunc(LPVOID lpdwParam) {
  18.         int tid = (int)lpdwParam;
  19.         int s = 0;
  20.         int i;
  21.         int dn = nmax / threadCount;
  22.         int start = tid * dn;
  23.         int stop = tid != threadCount - 1 ? (tid + 1)*dn : nmax;
  24.         for (i = start; i<stop; i++) s += t[i];
  25.         // Get into critical section
  26.         EnterCriticalSection(&cs);
  27.         sum += s;
  28.         // Leave critical section
  29.         LeaveCriticalSection(&cs);
  30.         return 0;
  31. }
  32.  
  33. int _tmain(int argc, _TCHAR* argv[])
  34. {
  35.         DWORD dwThreadId, dwThrdParam[threadCount];
  36.         HANDLE ahThreads[threadCount];
  37.  
  38.         InitializeCriticalSection(&cs);
  39.  
  40.         int i, s = 0, z = 100;
  41.         for (i = 0; i<nmax; i++) t[i] = rand() % z;
  42.  
  43.         //sequential
  44.         s = 0;
  45.         int time = GetTickCount();
  46.         for (i = 0; i<nmax; i++) s += t[i];
  47.         std::cout << "Sequential sum: " << s << std::endl;
  48.         time = time - GetTickCount();
  49.         std::cout << "Sequential sum time: " << s/10000 << " ticks of clock [*10000]" <<  std::endl;
  50.         //parallel
  51.         sum = 0;
  52.         time = GetTickCount();
  53.         for (i = 0; i<threadCount; i++)
  54.         {
  55.                 dwThrdParam[i] = i;
  56.                 ahThreads[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)dwThrdParam[i], 0, &dwThreadId);
  57.         }
  58.         for (i = 0; i<threadCount; i++)
  59.         {
  60.                 WaitForMultipleObjects(threadCount, ahThreads, true, INFINITE);
  61.         }
  62.         time = time - GetTickCount();
  63.         std::cout << std::endl;
  64.  
  65.         std::cout << "Parallel sum: " << sum << std::endl;
  66.         std::cout << "Parallel sum time: " << s / 10000 << " ticks of clock [*10000]" << std::endl;
  67.         DeleteCriticalSection(&cs);
  68.         std::cin.ignore(2);
  69.         return 0;
  70. }