您的位置:首页 > 其它

使用信号量进行线程同步

2011-09-24 22:40 246 查看
#include <windows.h>
#include <stdio.h>

#define NUMTHREADS 4

HANDLE hSemaphore;

void UseSemaphore(void);
DWORD WINAPI SemaphoreThread(LPVOID lpParam);

int main(void){
UseSemaphore();
}

void UseSemaphore(void){
HANDLE hThread[NUMTHREADS];
INT i;
LONG lMax;
CHAR cMax;
printf("将创建%d个线程,获得信号量的线程可以向屏幕打印.\n请输入信号量的最大计数1-%d:",NUMTHREADS,NUMTHREADS);
cMax = getch();
printf("%c\n",cMax);
lMax = cMax & 0xF;
if(lMax<0 || lMax>NUMTHREADS){
printf("请输入1-%d.\n",NUMTHREADS);
}
hSemaphore = CreateSemaphore(NULL,lMax,lMax,NULL);
if(hSemaphore == NULL){
printf("Create Semaphorec error.(%d)\n",GetLastError());
}
for(i=0;i<NUMTHREADS;i++){
hThread[i] = CreateThread(NULL,0,SemaphoreThread,&i,0,NULL);
if(hThread[i] == NULL){
printf("Create Threads error.(%d)\n",GetLastError());
return;
}
}
WaitForMultipleObjects(NUMTHREADS,hThread,TRUE,INFINITE);
}

DWORD WINAPI SemaphoreThread(LPVOID lpParam){
DWORD dwWaitResult;
BYTE lpRead[16];
DWORD j = 0;
DWORD dwPreviousCount;

for(;j<3;j++){
Sleep(rand()%1000);
dwWaitResult = WaitForSingleObject(hSemaphore,INFINITE);
switch(dwWaitResult){
case WAIT_OBJECT_0:
printf("\nProcess %d Gets Semaphore",GetCurrentThreadId());
break;
default:
printf("\nprocess %u wait error:%u",GetCurrentThreadId(),GetLastError());
}
Sleep(rand()%1000);
if(!ReleaseSemaphore(hSemaphore,1,&dwPreviousCount))
{
printf("\nprocess %u Release Semaphore error:%d",GetCurrentProcessId(),GetLastError());
}else
{
printf("\nProcess %u Release Semaphore,previous count is %u",GetCurrentProcessId(),dwPreviousCount);
}
}
return 1;
}


本文出自 “About:Blank H4cking” 博客,请务必保留此出处http://pnig0s1992.blog.51cto.com/393390/673401
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: