프로그래밍/API
쓰레드 - 세마포어
에어버스
2017. 1. 8. 14:24
쓰레드 - 세마포어
뮤텍스와 유사하며 임계영역이 1개인 경우 바이너리(Binary) 세마포어라고 하는데 이는 뮤텍스와 동일한 기능을 제공한다.
카운팅 기능을 제공한다.
동시 접근 가능한 쓰레드가 10개라면, 이 카운터가 0이 되면 NON-SIGNAL 상태가 된다.
이 카운팅은 WaitForSingleObject() 호출되면 1개 감소하고 RelaseSemaphore() 호출되면 1 증가한다.
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 |
#include "stdafx.h"
#include <Windows.h>
#include <process.h>
#include <tchar.h>
#include <locale.h>
#include <time.h>
#define NUM_OF_CUSTOMER 50
#define RANGE_MIN 10
#define RANGE_MAX (30 - RANGE_MIN)
#define TABLE_CNT 10
HANDLE hSemaphore;
DWORD randTimeArr[50];
void TakeMeal(DWORD time)
{
WaitForSingleObject(hSemaphore, INFINITE); // 카운팅 증가
_tprintf(_T("Enter customer %d\n"), GetCurrentThreadId());
_tprintf(_T("Customer %d having launch\n"), GetCurrentThreadId());
Sleep(1000 * time);
ReleaseSemaphore(hSemaphore, 1, NULL); // 카운팅 감소
_tprintf(_T("Out customer %d\n"), GetCurrentThreadId());
}
unsigned int WINAPI ThreadProc(LPVOID lParam)
{
TakeMeal((DWORD)lParam);
return 0;
}
int main()
{
_wsetlocale(LC_ALL, L"korean"); // #include <locale.h>필요, 유니코드에서 한글출력, wprintf(), fputws() 호출 전에 먼저 호출되야한다.
DWORD dwThreadIDs[NUM_OF_CUSTOMER];
HANDLE hThreads[NUM_OF_CUSTOMER];
srand((unsigned)time(NULL));
for (int i = 0; i < NUM_OF_CUSTOMER; i++)
randTimeArr[i] = (DWORD)((double)rand() / (double)RAND_MAX) * RANGE_MAX + RANGE_MIN;
hSemaphore = CreateSemaphore(
NULL,
TABLE_CNT, // 세마포어 초기값
TABLE_CNT, // 세마포어 최대값
NULL);
if (hSemaphore == NULL)
_tprintf(_T("세마포어 생성실패 %d"), GetLastError());
for (int i = 0; i < NUM_OF_CUSTOMER; i++)
{
hThreads[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, (void*)randTimeArr[i], CREATE_SUSPENDED, (unsigned*)&dwThreadIDs[i]);
if (hThreads[i] == NULL)
{
_tprintf(_T("쓰레드 생성 실패\n"));
return -1;
}
}
for (int i = 0; i < NUM_OF_CUSTOMER; i++)
ResumeThread(hThreads[i]);
WaitForMultipleObjects(NUM_OF_CUSTOMER, hThreads, TRUE, INFINITE);
_tprintf(_T("---------End-------\n"));
for (int i = 0; i < NUM_OF_CUSTOMER; i++)
CloseHandle(hThreads[i]);
CloseHandle(hSemaphore);
_tprintf(_T("키 입력 후 엔터키를 치세요....\n"));
getchar();
return 0;
}
|
cs |