Windows_41_thread_semaphore Thread-Signal

Source: Internet
Author: User

Windows_41_thread_semaphore Thread-Signal
  
 
  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 ] Span class= "pun" >= 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. }



From for notes (Wiz)

Windows_41_thread_semaphore Thread-Signal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.