Advertisement
Dyzio

SO_Sekcje_Krytyczne

Mar 29th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <Windows.h>
  3. #include <conio.h>
  4.  
  5. #define SIZE 200
  6. #define BIG 8000
  7. volatile char queue[SIZE];
  8. int j = 0;
  9.  
  10.  
  11. CRITICAL_SECTION critsection;
  12.  
  13. DWORD WINAPI th1(void *p)
  14. {
  15.     while (1)
  16.     {  
  17.         EnterCriticalSection(&critsection);
  18.         queue[++j] = 'K';
  19.         if (j > SIZE ) j = 0;
  20.         for (int k = 0; k < BIG; k++) {}
  21.         LeaveCriticalSection(&critsection);
  22.     }
  23. }
  24.  
  25. DWORD WINAPI th2(void *p)
  26. {
  27.     while (1)
  28.     {
  29.         EnterCriticalSection(&critsection);
  30.         queue[++j] = 'X';
  31.         if (j > SIZE ) j = 1;
  32.         for(int k = 0 ; k < BIG ; k++) { }
  33.         LeaveCriticalSection(&critsection);
  34.     }
  35. }
  36.  
  37. int main()
  38. {
  39.     InitializeCriticalSection(&critsection);
  40.  
  41.     HANDLE H1 = CreateThread(0, 0, th1, 0, 0, 0);
  42.     HANDLE H2 = CreateThread(0, 0, th2, 0, 0, 0);
  43.  
  44.  
  45.     while (!_kbhit())
  46.     {
  47.         for (int i = 0; i < SIZE; i++)
  48.             printf("%c,", queue[i]);
  49.         printf("\n");
  50.         Sleep(1000);
  51.     }
  52.  
  53.     CloseHandle(H1);
  54.     CloseHandle(H2);
  55.     DeleteCriticalSection(&critsection);
  56.  
  57.     return 0;
  58. }
  59.  
  60. /* Wydruk
  61. ,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,
  62. K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,
  63. K,K,K,K,K,K,K,K,K,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,
  64. X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,
  65. X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,K,K,K,K,K,K,K,K,K,K,K,
  66. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement