Advertisement
ozimas

PO zad. 2.2

Jan 20th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <stdlib.h>
  3. #include <Windows.h>
  4.  
  5. int suma;
  6. int t[10000];
  7.  
  8. CRITICAL_SECTION cs;
  9.  
  10. DWORD WINAPI ThreadFunc(LPVOID lpdwParam) {
  11.     int tid = (int)lpdwParam;
  12.     int s = 0;
  13.     int i;
  14.     int dn = 10000 / 4;
  15.     int start = tid*dn;
  16.     int stop = tid != 4 - 1 ? (tid + 1)*dn : 10000;
  17.     for (i = start; i<stop; i++) s += t[i];
  18.     EnterCriticalSection(&cs);
  19.     suma += s;
  20.     LeaveCriticalSection(&cs);
  21.     return 0;
  22. }
  23.  
  24. int _tmain(int argc, _TCHAR* argv[])
  25. {
  26.     DWORD dwThreadId, dwThrdParam[4];
  27.     HANDLE ahThreads[4];
  28.     InitializeCriticalSection(&cs);
  29.  
  30.     int i, s = 0, z = 100;
  31.     for (i = 0; i<10000; i++) t[i] = rand() % z;
  32.  
  33.     s = 0;
  34.     for (i = 0; i<10000; i++) s += t[i];
  35.     printf("Suma wyliczona przez watek 1: %d\n", s);
  36.     suma = 0;
  37.  
  38.     for (i = 0; i<4; i++)
  39.     {
  40.         dwThrdParam[i] = i;
  41.         ahThreads[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)dwThrdParam[i], 0, &dwThreadId);
  42.     }
  43.     for (i = 0; i<4; i++)
  44.     {
  45.         WaitForMultipleObjects(4, ahThreads, true, INFINITE);
  46.     }
  47.     printf("Suma wyliczona przez watek 2: %d\n", suma);
  48.     DeleteCriticalSection(&cs);
  49.     system("pause");
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement