Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Feb 10th, 2012  |  syntax: C  |  size: 1.51 KB  |  hits: 74  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4.  
  5. #define N 100
  6.  
  7. typedef struct {
  8.   int number[N];
  9.   int choosing[N];
  10. } lock;
  11.  
  12. void
  13. Init(lock l)
  14. {
  15.   int i;
  16.   for (i = 0; i < N; ++i)
  17.     {
  18.       l.choosing[i] = l.number[i] = 0;
  19.     }
  20. }
  21.  
  22. int
  23. Max(int* a, int length)
  24. {
  25.   int i;
  26.   int max = a[0];
  27.   for (i = 1; i < length; ++i)
  28.     {
  29.       if (a[i] > max)
  30.         max = a[i];
  31.     }
  32.  
  33.   return max;
  34. }
  35.  
  36. void
  37. Lock(lock l, int id)
  38. {
  39.   l.choosing[id] = 1;
  40.   l.number[id] = Max(l.number, N) + 1;
  41.   l.choosing[id] = 0;
  42.  
  43.  
  44.   int j;
  45.   for (j = 0; j < N; j++)
  46.     {
  47.       if (j == id)
  48.         continue;
  49.  
  50.       while (1)
  51.         {
  52.           if (l.choosing[j] == 0)
  53.             break;
  54.         }
  55.  
  56.       while (1)
  57.         {
  58.           if (l.number[j] == 0)
  59.             break;
  60.           if ((l.number[j] > l.number[id])
  61.               || (l.number[j] == l.number[id] && j > id))
  62.             break;
  63.         }
  64.     }
  65. }
  66.  
  67. void
  68. Unlock(lock l, int id)
  69. {
  70.   l.number[id] = 0;
  71. }
  72.  
  73. lock LOCK;
  74. int counter;
  75.  
  76. void*
  77. thread_code(void* data)
  78. {
  79.   int id = (long) data;
  80.  
  81.  
  82.   int i;
  83.   for (i = 0; i < 10; ++i)
  84.     {
  85.       Lock(LOCK, id);
  86.       counter++;
  87.       Unlock(LOCK, id);
  88.     }
  89. }
  90.  
  91.  
  92. int
  93. main(int argc, char* argv[])
  94. {
  95.   counter = 0;
  96.   Init(LOCK);
  97.   pthread_t threads[N];
  98.  
  99.   int i;
  100.   for (i = 0; i < N; i++) {
  101.     pthread_create(&threads[i], NULL, thread_code, (void *) i);
  102.   }
  103.  
  104.   for (i = 0; i < N; i++) {
  105.     pthread_join(threads[i], NULL);
  106.   }
  107.  
  108.   printf("Counter: %d\n", counter);
  109.   return 0;
  110. }