1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | #include <iostream> #include <string.h> #include <Windows.h> using namespace std; #define SizeOfArray 10 #define SizeOfThread 3 #define Term SizeOfArray/SizeOfThread DWORD WINAPI InPut(LPVOID pParam); DWORD WINAPI Sum(LPVOID pParam); struct MyStruct { int array[SizeOfArray]; int where; HANDLE hThread[SizeOfThread]; HANDLE hMutex; CRITICAL_SECTION _thislock; DWORD dwThreadID[SizeOfThread]; int total; void initialize() { total = 0; where = 0; hMutex = CreateMutex(NULL, FALSE, NULL); // 스레드들이 값을 더하는 동기화 InitializeCriticalSection(&_thislock); } void Execute() { hThread[0] = CreateThread(NULL, 0, InPut, this, 0, &dwThreadID[0]); for (int i = 1; i < SizeOfThread; i++) { hThread[i] = CreateThread(NULL, 0, Sum, this, 0, &dwThreadID[i]); } WaitForMultipleObjects(SizeOfThread, hThread, TRUE, INFINITE); } void print() { for (int i = 0; i < SizeOfArray; i++) cout << array[i] << ", "; cout << endl; cout << total; } ~MyStruct() { CloseHandle(hMutex); DeleteCriticalSection(&_thislock); for (int i = 0; i < SizeOfThread;i++) CloseHandle(hThread[i]); } }; DWORD WINAPI InPut(LPVOID pParam) { MyStruct* ms = (MyStruct*)pParam; WaitForSingleObject(ms->hMutex, INFINITE); for (int i = 0; i < SizeOfArray; i++) cin >> ms->array[i]; ReleaseMutex(ms->hMutex); return 0; } DWORD WINAPI Sum(LPVOID pParam) { MyStruct* ms = (MyStruct*)pParam; WaitForSingleObject(ms->hMutex, INFINITE); EnterCriticalSection(&ms->_thislock); if (ms->where < Term*(SizeOfThread -1)) { for (int i = 0; i < Term*(SizeOfThread - 1); i++) { ms->total += ms->array[ms->where]; ms->where += 1; } } else{ while (ms->where != SizeOfArray) { ms->total += ms->array[ms->where]; ms->where += 1; } } LeaveCriticalSection(&(ms->_thislock)); ReleaseMutex(ms->hMutex); return 0; } int main() { struct MyStruct ms; ms.initialize(); ms.Execute(); ms.print(); ms.~MyStruct(); return 0; } | cs |
이번 코드는 확실히 전 코드 보다 발전했던 걸까..?
'시스템프로그래밍' 카테고리의 다른 글
간단한 채팅서버 구현시 오류났던 부분 (0) | 2018.05.30 |
---|---|
이벤트를 사용한 예제 (0) | 2018.05.26 |
크리티컬 섹션과 파일입출력을 통한 기본예제.. (0) | 2018.05.26 |
크리티컬 섹션을 이용한 기본예제.. (0) | 2018.05.26 |
멀티프로세스 기본예제 (0) | 2018.05.26 |