创建信号量:HANDLE CreateSemaphore (LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCTSTR lpName);1:lpSemaphoreAttributes应设为NULL;2:lInitialCount信号量的初始态,必须大于等于0;3:MaximumCount信号量允许的最大计数值,必须大于0.注意lInitialCount应小于等于MaximumCount,否则会创建失败4:lpName可选的对象命名释放信号量:BOOL ReleaseSemaphore (HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount);1:hSemaphore,信号量句柄2:lReleaseCount,信号量计数器增加的数值3:lpPreviousCount,接收信号量前一次资源的计数值
// MyThread.cpp : Defines the entry point for the console application. //
#include "stdafx.h" #include <windows.h> #include <commctrl.h>
HANDLE hSem;
DWORD MyThread1(VOID) { INT32 i = 0;
while(1) { WaitForSingleObject(hSem, INFINITE); printf("1:%d/n",i++); ReleaseSemaphore(hSem,1,NULL); }
return 0; }
DWORD MyThread2(VOID) { INT32 i = 0;
while(1) { WaitForSingleObject(hSem, INFINITE); printf("2:%d/n",i++); ReleaseSemaphore(hSem,1,NULL); }
return 0; }
int _tmain(int argc, _TCHAR* argv[]) { HANDLE hThread1; HANDLE hThread2;
hSem = CreateSemaphore(NULL, 0, 1, NULL); if(NULL == hSem) { printf("Create hSem error/n"); return -1; }
hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread1, NULL, 0, NULL); if(hThread1) { printf("CreateThread MyThread1 success/r/n"); } else { printf("CreateThread MyThread1 error/r/n"); return -1; }
hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread2, NULL, 0, NULL); if(hThread2) { printf("CreateThread MyThread2 success/r/n"); } else { printf("CreateThread MyThread2 error/r/n"); return -1; }
Sleep(5000); ReleaseSemaphore(hSem,1,NULL);
while(1) { Sleep(1000); }
CloseHandle(hThread1); CloseHandle(hThread2);
return 0; } |