Guest User

Untitled

a guest
Feb 10th, 2017
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. #include <string.h> // strcpy
  5. #include <unistd.h> // usleep
  6.  
  7. #define MICROS (1)
  8. #define THREADS (5)
  9. #define ACCESSES (5)
  10.  
  11. char * names[] = {"alpha",   "bravo",    "charlie", "delta",
  12.                   "echo",    "foxtrot",  "golf",    "hotel",
  13.                   "india",   "juliet",   "kilo",    "lima",
  14.                   "mike",    "november", "oscar",   "papa",
  15.                   "quebec",  "romeo",    "sierra",  "tango",
  16.                   "uniform", "victor",   "whiskey", "x-ray",
  17.                   "yankee",  "zulu"};
  18.  
  19. // could be a good idea to use XCHG asm operation as atomic
  20.  
  21. void mutex_lock();
  22. void mutex_unlock();
  23.  
  24. int mx = 0;
  25. int counter = 0;
  26. char pool[128] = {0};
  27. pthread_t threads[THREADS];
  28.  
  29. void fill_pool()
  30. {
  31.     counter++;
  32.     strcpy(pool, names[random() % 26]);
  33. }
  34.  
  35. void show_pool(int number)
  36. {
  37.     printf("%04d - %04d - %s\n", counter, number, pool);
  38. }
  39.  
  40. void * thread_fnc(void * index)
  41. {
  42.     int number = (int)index;
  43.     int i;
  44.     for (i = 0; i < ACCESSES; i++)
  45.     {
  46.         usleep(random() % 10000);
  47.         mutex_lock();
  48.         {
  49.             fill_pool();
  50.             show_pool(number);
  51.         }
  52.         mutex_unlock();
  53.     }    
  54. }
  55.  
  56. void mutex_lock()
  57. {
  58.     while (mx) /* needs atomic */
  59.     {
  60.         usleep(MICROS);
  61.     }
  62.  
  63.     mx = 1;
  64. }
  65.  
  66. void mutex_unlock()
  67. {
  68.     mx = 0;
  69. }
  70.  
  71. int main()
  72. {
  73.     int i;    
  74.  
  75.     printf(" ##  - THRD - name\n");    
  76.  
  77.     for (i = 0; i < THREADS; i++)
  78.         pthread_create(&threads[i], NULL, thread_fnc, (void *)i);
  79.  
  80.     for (i = 0; i < THREADS; i++)
  81.         pthread_join(threads[i], NULL);
  82.  
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment