41 windows_41_Thread_Semaphore 线程 - 信号

windows_41_Thread_Semaphore 线程 - 信号


  1. // windows_41_Thread_Semaphore.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include "windows.h"
  5. /*
  6. 效果:前面很快出五个,后面一秒出一个
  7. */
  8. //1、创建信号量
  9. //CreateSemaphore
  10. //2、等候信号量
  11. //WaitForSingleObject
  12. //WaitForMultipleObjects
  13. //3、释放信号
  14. //ReleaseSemaphore
  15. //4、关闭信号量
  16. //CloseHandle
  17. HANDLE g_hSemaphore = NULL;
  18. //输入1或者5发送1或者5个信号量
  19. DWORD WINAPI ThreadSend3( LPVOID pParam )
  20. {
  21. while (true)
  22. {
  23. //3、释放信号
  24. //ReleaseSemaphore
  25. Sleep( 1000 );
  26. CHAR ch = getchar( );
  27. switch (ch)
  28. {
  29. case '1':
  30. //释放信号
  31. ReleaseSemaphore( g_hSemaphore, 1, NULL );
  32. break;
  33. case '5':
  34. ReleaseSemaphore( g_hSemaphore, 5, NULL );
  35. break;
  36. }
  37. }
  38. return 0;
  39. }
  40. DWORD WINAPI ThreadSend( LPVOID pParam )
  41. {
  42. while (true)
  43. {
  44. //3、释放信号
  45. //ReleaseSemaphore
  46. ReleaseSemaphore( g_hSemaphore, 1, NULL );
  47. Sleep( 1000 );
  48. }
  49. return 0;
  50. }
  51. DWORD WINAPI ThreadRecv( LPVOID pParam )
  52. {
  53. while (true)
  54. {
  55. WaitForSingleObject( g_hSemaphore, INFINITE );
  56. printf( "Hello Semaphore\n" );
  57. Sleep( 100 );
  58. }
  59. return 0;
  60. }
  61. void Create( )
  62. {
  63. DWORD nThreadID = 0;
  64. HANDLE hThread[2] = { 0 };
  65. hThread[0] = CreateThread( NULL, 0, ThreadSend, NULL, 0 ,&nThreadID);
  66. hThread[1] = CreateThread( NULL, 0, ThreadRecv, NULL, 0 ,&nThreadID);
  67. // 等候两个线程的结束
  68. WaitForMultipleObjects( 2, hThread, TRUE, INFINITE );
  69. }
  70. int _tmain(int argc, _TCHAR* argv[])
  71. {
  72. //1、创建信号量
  73. //CreateSemaphore
  74. g_hSemaphore = CreateSemaphore( NULL, 5, 10, NULL );
  75. Create( );
  76. //4、关闭信号量
  77. //CloseHandle
  78. CloseHandle( g_hSemaphore );
  79. return 0;
  80. }





posted @ 2016-06-10 20:45  -刀狂剑痴-  阅读(224)  评论(0编辑  收藏  举报