使用信号量进行线程同步
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
相关文章推荐
- 使用sem_post信号量进行线程同步
- 使用信号量 进行windows线程同步 (Semaphore)
- Windows核心编程笔记(九)使用内核对象进行线程同步
- [多线程]使用信号量进行同步
- 网络编程(39)—— 使用信号量semaphore进行多线程同步
- 如何使用java synchronized进行线程同步
- 使用信号量进行线程间同步
- 改善C#程序的建议6:在线程同步中使用信号量
- 使用java中的 synchronized进行线程同步
- Linux线程同步(二)之使用信号量
- 如何使用java synchronized进行线程同步
- C# 使用ManualResetEvent 进行线程同步
- 第九章 使用内核对象进行线程同步
- 使用互斥量进行线程同步,与关键段和事件的区别
- C++使用信号量对象实现线程同步
- 如何使用java synchronized进行线程同步
- 改善C#程序的建议6:在线程同步中使用信号量
- 使用dispatch_group来进行线程同步
- VB.NET中使用监控类进行线程同步
- 如何使用java synchronized进行线程同步