Programming/C++
- 2016. 3. 7. 12:17
멀티쓰레드 크리티컬 섹션 연습
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | #include <iostream> #include <windows.h> #include <process.h> #define THREAD_COUNT 2 CRITICAL_SECTION crs; int number = 0; unsigned int __stdcall threadFun1( void *lpVoid) { //함수 입장 및 크리티컬 섹션 사용 std::cout << "Enter : " << __FUNCTION__ << std::endl; EnterCriticalSection(&crs); std::cout << "EnterCriticalsection : " << __FUNCTION__ << std::endl; for ( int i = 0; i < 10; i++) { std::cout << number << __FUNCTION__ << std::endl; number++; } //크리티컬 섹션 끝냄 및 함수 종료 std::cout << "EndCriticalsection : " << __FUNCTION__ << std::endl; LeaveCriticalSection(&crs); std::cout << "End : " << __FUNCTION__ << std::endl; //_endthreadex(0); 생략 가능 return 0; } unsigned int __stdcall threadFun2( void *lpVoid) { //함수 입장 및 크리티컬 섹션 사용 std::cout << "Enter : " << __FUNCTION__ << std::endl; EnterCriticalSection(&crs); std::cout << "EnterCriticalsection : " << __FUNCTION__ << std::endl; for ( int i = 0; i < 15; i++) { std::cout << number << __FUNCTION__ << std::endl; number++; } //크리티컬 섹션 끝냄 및 함수 종료 std::cout << "EndCriticalsection : " << __FUNCTION__ << std::endl; LeaveCriticalSection(&crs); std::cout << "End : " << __FUNCTION__ << std::endl; //_endthreadex(0); 생략 가능 return 0; } int main() { HANDLE hThread[THREAD_COUNT]; InitializeCriticalSection(&crs); //크리티컬 섹션 생성 hThread[0] = ( HANDLE )_beginthreadex(NULL, 0, threadFun1, NULL, 0, NULL); hThread[1] = ( HANDLE )_beginthreadex(NULL, 0, threadFun2, NULL, 0, NULL); WaitForMultipleObjects(THREAD_COUNT, hThread, true , INFINITE); CloseHandle(hThread[0]); CloseHandle(hThread[1]); DeleteCriticalSection(&crs); //크리티컬 섹션 삭제 return 0; } |
결과 화면
(네이버 블로그 - 2016.02.01. 18:44)
'Programming > C++' 카테고리의 다른 글
멀티쓰레드 이벤트 연습 (0) | 2016.03.07 |
---|---|
멀티쓰레드 뮤텍스 연습 (0) | 2016.03.07 |
멀티쓰레드 기본적인 연습(_beginthreadex()) (0) | 2016.03.07 |
멀티쓰레드 연습(win32 api(CreateThread)) (0) | 2016.03.07 |
(링크) 멀티쓰레드 공부 (0) | 2016.03.07 |