Advertisement
Guest User

Untitled

a guest
Jan 19th, 2020
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <Windows.h>
  3. #include <time.h>
  4.  
  5. #define TIMES_TO_EAT 1000000
  6.  
  7. CRITICAL_SECTION sticks[5] = { 0 };
  8. HANDLE all[5];
  9.  
  10.  
  11. DWORD WINAPI philosEat(LPVOID param)
  12. {
  13.     int n = TIMES_TO_EAT;
  14.     int i = 1;
  15.  
  16.     int id = *(int*)param;
  17.  
  18.     while (i != n + 1)
  19.     {
  20.         if (TryEnterCriticalSection(&(sticks[id % 5])))
  21.         {
  22.             if (TryEnterCriticalSection(&(sticks[id - 1])))
  23.             {
  24.                 printf("%d Eating now: %d\n", id, i);
  25.                 i++;
  26.                 LeaveCriticalSection(&sticks[id - 1]);
  27.             }
  28.             LeaveCriticalSection(&(sticks[id % 5]));
  29.         }
  30.     }
  31.  
  32.     printf("%d Done!\n", id);
  33. }
  34.  
  35.  
  36. int main()
  37. {
  38.     int id1 = 1;
  39.     int id2 = 2;
  40.     int id3 = 3;
  41.     int id4 = 4;
  42.     int id5 = 5;
  43.  
  44.     InitializeCriticalSection(&sticks[0]);
  45.     InitializeCriticalSection(&sticks[1]);
  46.     InitializeCriticalSection(&sticks[2]);
  47.     InitializeCriticalSection(&sticks[3]);
  48.     InitializeCriticalSection(&sticks[4]);
  49.  
  50.     clock_t begin = clock();
  51.  
  52.     HANDLE phil1 = CreateThread(NULL, 0, philosEat, &id1, 0, NULL);
  53.     HANDLE phil2 = CreateThread(NULL, 0, philosEat, &id2, 0, NULL);
  54.     HANDLE phil3 = CreateThread(NULL, 0, philosEat, &id3, 0, NULL);
  55.     HANDLE phil4 = CreateThread(NULL, 0, philosEat, &id4, 0, NULL);
  56.     HANDLE phil5 = CreateThread(NULL, 0, philosEat, &id5, 0, NULL);
  57.  
  58.     all[0] = phil1;
  59.     all[1] = phil2;
  60.     all[2] = phil3;
  61.     all[3] = phil4;
  62.     all[4] = phil5;
  63.    
  64.     WaitForMultipleObjects(5, all, 1, INFINITE);
  65.    
  66.     clock_t end = clock();
  67.  
  68.     printf("Time: %lf seconds\n", ((double)end - begin) / CLOCKS_PER_SEC);
  69.  
  70.     CloseHandle(phil1);
  71.     CloseHandle(phil2);
  72.     CloseHandle(phil3);
  73.     CloseHandle(phil4);
  74.     CloseHandle(phil5);
  75.  
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement