Advertisement
andruhovski

ossp-demo-20160928

Sep 28th, 2016
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. // ossp-demo-20160928.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <process.h>
  6. #include <windows.h>
  7.  
  8. void __cdecl my_thread(void *);
  9. CRITICAL_SECTION CriticalSection;
  10. int queue = 0;
  11.  
  12. int _tmain(int argc, _TCHAR* argv[])
  13. {
  14.     char a = 'A', b = 'B', c = 'C', d = 'D', e = 'E';
  15.     HANDLE handles[5];
  16.  
  17.     // Initialize the critical section one time only.
  18.     if (!InitializeCriticalSectionAndSpinCount(&CriticalSection,
  19.         0x00000400))
  20.         return 0;
  21.  
  22.     //запустити my_thread('A');
  23.     handles[0]=  (HANDLE)_beginthread(my_thread, 0, &a);
  24.     //запустити my_thread('B');
  25.     handles[1] = (HANDLE)_beginthread(my_thread, 0, &b);
  26.     //запустити my_thread('C');
  27.     handles[2] = (HANDLE)_beginthread(my_thread, 0, &c);
  28.     //запустити my_thread('D');
  29.     handles[3] = (HANDLE)_beginthread(my_thread, 0, &d);
  30.     //запустити my_thread('E');
  31.     handles[4] = (HANDLE)_beginthread(my_thread, 0, &e);
  32.  
  33.     WaitForMultipleObjects(5, handles, TRUE, INFINITE);
  34.  
  35.     // Release resources used by the critical section object.
  36.     DeleteCriticalSection(&CriticalSection);
  37.     return 0;
  38. }
  39.  
  40. void __cdecl my_thread(void *arg)
  41. {
  42.     char *ch = (char *)arg;
  43.     for (size_t i = 0; i < 10;)
  44.     {
  45.         // Request ownership of the critical section.
  46.         EnterCriticalSection(&CriticalSection);
  47.         if (queue == (*ch - 65))
  48.         {
  49.             putchar(*ch);
  50.             queue = (queue + 1) % 5;
  51.             i++;
  52.             if (*ch == 'E')
  53.                 putchar('\n');
  54.         }
  55.         // Release ownership of the critical section.
  56.         LeaveCriticalSection(&CriticalSection);
  57.         Sleep(200);
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement