gallir

peterson-not-working

Oct 7th, 2014
630
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.     while (estado[other] && turno == other);
  20. }
  21.  
  22. void s_peterson(int id) {
  23.     estado[id] = 0;
  24. }
  25.  
  26. void *counter(void *threadid) {
  27.     long tid, i, max = MAX_COUNT/NUM_THREADS;
  28.     tid = (long)threadid;
  29.  
  30.     for (i=0; i < max; i++) {
  31.         e_peterson(tid);
  32.         count++; //SC
  33.         s_peterson(tid);
  34.     }
  35.  
  36.     pthread_exit(NULL);
  37. }
  38.  
  39. int main (int argc, char *argv[]) {
  40.     pthread_t threads[NUM_THREADS];
  41.     int rc;
  42.     long t;
  43.  
  44.     estado[0] = 0;
  45.     estado[1] = 0;
  46.     turno = 0;
  47.  
  48.     for(t=0; t<NUM_THREADS; t++){
  49.         rc = pthread_create(&threads[t], NULL, counter, (void *)t);
  50.         if (rc){
  51.             printf("ERROR; return code from pthread_create() is %d\n", rc);
  52.             exit(-1);
  53.         }
  54.     }
  55.  
  56.     for(t=0; t<NUM_THREADS; t++){
  57.         pthread_join(threads[t], NULL);
  58.     }
  59.  
  60.     float error = (MAX_COUNT-count)/(float) MAX_COUNT *100;
  61.  
  62.     printf("Final result: %ld Expected: %ld Diff: %ld Error: %3.2f%%\n", count, MAX_COUNT, count-MAX_COUNT, error);
  63.  
  64.     puts("Bye from main");
  65.     pthread_exit(NULL);
  66. }
RAW Paste Data