Advertisement
gallir

peterson-working

Oct 7th, 2014
901
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5.  
  6.  
  7. #define NUM_THREADS  2
  8. #define MAX_COUNT 1000000L
  9.  
  10. volatile long count = 0;
  11. volatile int estado[NUM_THREADS];
  12. volatile int turno;
  13.  
  14. void e_peterson(int id) {
  15.     int other = (id +1) % NUM_THREADS;
  16.  
  17.     estado[id] = 1;
  18.     turno = other;
  19.     __sync_synchronize();
  20.     while (estado[other] && turno == other);
  21. }
  22.  
  23. void s_peterson(int id) {
  24.     estado[id] = 0;
  25. }
  26.  
  27. void *counter(void *threadid) {
  28.     long tid, i, max = MAX_COUNT/NUM_THREADS;
  29.     tid = (long)threadid;
  30.  
  31.     for (i=0; i < max; i++) {
  32.         e_peterson(tid);
  33.         count++; //SC
  34.         s_peterson(tid);
  35.     }
  36.  
  37.     pthread_exit(NULL);
  38. }
  39.  
  40. int main (int argc, char *argv[]) {
  41.     pthread_t threads[NUM_THREADS];
  42.     int rc;
  43.     long t;
  44.  
  45.     estado[0] = 0;
  46.     estado[1] = 0;
  47.     turno = 0;
  48.  
  49.  
  50.     for(t=0; t<NUM_THREADS; t++){
  51.         rc = pthread_create(&threads[t], NULL, counter, (void *)t);
  52.         if (rc){
  53.             printf("ERROR; return code from pthread_create() is %d\n", rc);
  54.             exit(-1);
  55.         }
  56.     }
  57.  
  58.     for(t=0; t<NUM_THREADS; t++){
  59.         pthread_join(threads[t], NULL);
  60.     }
  61.  
  62.     float error = (MAX_COUNT-count)/(float) MAX_COUNT *100;
  63.  
  64.     printf("Final result: %ld Expected: %ld Diff: %ld Error: %3.2f%%\n", count, MAX_COUNT, count-MAX_COUNT, error);
  65.  
  66.     puts("Bye from main");
  67.     pthread_exit(NULL);
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement