Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <stdlib.h>
- #include <Windows.h>
- int suma;
- int t[10000];
- CRITICAL_SECTION cs;
- DWORD WINAPI ThreadFunc(LPVOID lpdwParam) {
- int tid = (int)lpdwParam;
- int s = 0;
- int i;
- int dn = 10000 / 4;
- int start = tid*dn;
- int stop = tid != 4 - 1 ? (tid + 1)*dn : 10000;
- for (i = start; i<stop; i++) s += t[i];
- EnterCriticalSection(&cs);
- suma += s;
- LeaveCriticalSection(&cs);
- return 0;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- DWORD dwThreadId, dwThrdParam[4];
- HANDLE ahThreads[4];
- InitializeCriticalSection(&cs);
- int i, s = 0, z = 100;
- for (i = 0; i<10000; i++) t[i] = rand() % z;
- s = 0;
- for (i = 0; i<10000; i++) s += t[i];
- printf("Suma wyliczona przez watek 1: %d\n", s);
- suma = 0;
- for (i = 0; i<4; i++)
- {
- dwThrdParam[i] = i;
- ahThreads[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)dwThrdParam[i], 0, &dwThreadId);
- }
- for (i = 0; i<4; i++)
- {
- WaitForMultipleObjects(4, ahThreads, true, INFINITE);
- }
- printf("Suma wyliczona przez watek 2: %d\n", suma);
- DeleteCriticalSection(&cs);
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement