스레드 동기화 Semaphore
4069 단어 Windows
스레드 동기화 신호량
Semaphore
신호량.
그것은 값이 0보다 크면 신호량 대상이 이미 전송된 상태를 유지하는 계수를 유지한다.일반적으로 사용 가능한 자원의 개수를 수치로 표시합니다.
WaitForSingleObject()는 신호량을 1로 줄입니다.ReleaseSemaphore()는 신호량을 1씩 증가시킵니다.//Semaphore
//this example is from msdn
#include
#include
#define MAX_SEM_COUNT 6
#define THREADCOUNT 8
HANDLE ghSemaphore;
DWORD WINAPI ThreadProc( LPVOID );
int main( void )
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
// Create a semaphore with initial and max counts of MAX_SEM_COUNT
ghSemaphore = CreateSemaphore(
NULL, // default security attributes
MAX_SEM_COUNT, // initial count
MAX_SEM_COUNT, // maximum count
NULL); // unnamed semaphore
if (ghSemaphore == NULL)
{
printf("CreateSemaphore error: %d
", GetLastError());
return 1;
}
// Create worker threads
for( i=0; i < THREADCOUNT; i++ ){
aThread[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) ThreadProc,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
if( aThread[i] == NULL ){
printf("CreateThread error: %d
", GetLastError());
return 1;
}
}
// Wait for all threads to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
// Close thread and semaphore handles
for( i=0; i < THREADCOUNT; i++ )
CloseHandle(aThread[i]);
CloseHandle(ghSemaphore);
return 0;
}
DWORD WINAPI ThreadProc( LPVOID lpParam )
{
// lpParam not used in this example
UNREFERENCED_PARAMETER(lpParam);
DWORD dwWaitResult;
BOOL bContinue=TRUE;
while(bContinue)
{
// Try to enter the semaphore gate.
dwWaitResult = WaitForSingleObject(
ghSemaphore, // handle to semaphore
1L); // zero-second time-out interval
switch (dwWaitResult)
{
// The semaphore object was signaled.
case WAIT_OBJECT_0:
// TODO: Perform task
printf("Thread %d: wait succeeded
", GetCurrentThreadId());
bContinue=FALSE;
// Simulate thread spending time on task
Sleep(5);
// Release the semaphore when task is finished
if (!ReleaseSemaphore(
ghSemaphore, // handle to semaphore
1, // increase count by one
NULL) ) // not interested in previous count
{
printf("ReleaseSemaphore error: %d
", GetLastError());
}
break;
// The semaphore was nonsignaled, so a time-out occurred.
case WAIT_TIMEOUT:
printf("Thread %d: wait timed out
", GetCurrentThreadId());
break;
}
}
return TRUE;
}
/*
Thread 7752: wait succeeded
Thread 9520: wait succeeded
Thread 10852: wait succeeded
Thread 5352: wait succeeded
Thread 8164: wait succeeded
Thread 10060: wait succeeded
Thread 4800: wait timed out
Thread 4516: wait timed out
Thread 4516: wait timed out
Thread 4800: wait timed out
Thread 4800: wait timed out
Thread 4800: wait succeeded
Thread 4516: wait timed out
Thread 4516: wait succeeded
. . .
*/
분석:
신호량 6, MAXSEM_COUNT, 신호량을 사용하는 라인은 8,THREADCOUNT이고main 함수 라인은 포함되지 않습니다.그래서 처음 6개의 만들어진 스레드WaitForSingleObject()가 WAIT 로 되돌아옵니다.OBJECT_0, 막히지 않습니다.다음 스레드 WaitForSingleObject()는 WAIT 로 반환됩니다.TIMEOUT, 다른 P 작업이 성공한 스레드Sleep(5)을 기다린 후 V 조작을 해야 WAIT 를 획득할 수 있습니다OBJECT_0은(는) 값을 반환합니다.8개의 ThreadProc 스레드가 실행되고 주 함수에서WaitForMultipleObjects () 함수가 되돌아옵니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[WinIoT/라즈파이] VS2019로 만든 UWP의 sln을 라즈파이 3+WinIoTCore로 원격 디버깅을 할 수 없을 때의 대처
2021년 1월 시점에서 라즈파이 3에 WindowsIoTCore를 넣고 VisualStudio2019에서 UWP 앱을 새로 만들고 디버깅하려고 했는데 잘 디버깅할 수 없었다.
구체적으로는, 「리모트 디버거에 접속할...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
//Semaphore
//this example is from msdn
#include
#include
#define MAX_SEM_COUNT 6
#define THREADCOUNT 8
HANDLE ghSemaphore;
DWORD WINAPI ThreadProc( LPVOID );
int main( void )
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
// Create a semaphore with initial and max counts of MAX_SEM_COUNT
ghSemaphore = CreateSemaphore(
NULL, // default security attributes
MAX_SEM_COUNT, // initial count
MAX_SEM_COUNT, // maximum count
NULL); // unnamed semaphore
if (ghSemaphore == NULL)
{
printf("CreateSemaphore error: %d
", GetLastError());
return 1;
}
// Create worker threads
for( i=0; i < THREADCOUNT; i++ ){
aThread[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) ThreadProc,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
if( aThread[i] == NULL ){
printf("CreateThread error: %d
", GetLastError());
return 1;
}
}
// Wait for all threads to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
// Close thread and semaphore handles
for( i=0; i < THREADCOUNT; i++ )
CloseHandle(aThread[i]);
CloseHandle(ghSemaphore);
return 0;
}
DWORD WINAPI ThreadProc( LPVOID lpParam )
{
// lpParam not used in this example
UNREFERENCED_PARAMETER(lpParam);
DWORD dwWaitResult;
BOOL bContinue=TRUE;
while(bContinue)
{
// Try to enter the semaphore gate.
dwWaitResult = WaitForSingleObject(
ghSemaphore, // handle to semaphore
1L); // zero-second time-out interval
switch (dwWaitResult)
{
// The semaphore object was signaled.
case WAIT_OBJECT_0:
// TODO: Perform task
printf("Thread %d: wait succeeded
", GetCurrentThreadId());
bContinue=FALSE;
// Simulate thread spending time on task
Sleep(5);
// Release the semaphore when task is finished
if (!ReleaseSemaphore(
ghSemaphore, // handle to semaphore
1, // increase count by one
NULL) ) // not interested in previous count
{
printf("ReleaseSemaphore error: %d
", GetLastError());
}
break;
// The semaphore was nonsignaled, so a time-out occurred.
case WAIT_TIMEOUT:
printf("Thread %d: wait timed out
", GetCurrentThreadId());
break;
}
}
return TRUE;
}
/*
Thread 7752: wait succeeded
Thread 9520: wait succeeded
Thread 10852: wait succeeded
Thread 5352: wait succeeded
Thread 8164: wait succeeded
Thread 10060: wait succeeded
Thread 4800: wait timed out
Thread 4516: wait timed out
Thread 4516: wait timed out
Thread 4800: wait timed out
Thread 4800: wait timed out
Thread 4800: wait succeeded
Thread 4516: wait timed out
Thread 4516: wait succeeded
. . .
*/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[WinIoT/라즈파이] VS2019로 만든 UWP의 sln을 라즈파이 3+WinIoTCore로 원격 디버깅을 할 수 없을 때의 대처2021년 1월 시점에서 라즈파이 3에 WindowsIoTCore를 넣고 VisualStudio2019에서 UWP 앱을 새로 만들고 디버깅하려고 했는데 잘 디버깅할 수 없었다. 구체적으로는, 「리모트 디버거에 접속할...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.