#include <pthread.h>
#include "eyebot.h"

pthread_mutex_t s[3], print;
int running = 1;


void *slave(void *arg)
{ int i = (int) arg;
  while(running)
  { pthread_mutex_lock(&s[i]);
    pthread_mutex_lock(&print);
      LCDPrintf("%d", i);
    pthread_mutex_unlock(&print);
    pthread_mutex_unlock(&s[i]);
  }
  return NULL;
}


void *master(void *arg)
{ while(running) 
  { switch (KEYRead())
    { case KEY1: pthread_mutex_unlock(&s[0]); break;
      case KEY2: pthread_mutex_unlock(&s[1]); break;
      case KEY3: pthread_mutex_unlock(&s[2]); break;
      case KEY4: running = 0; break;
    } 
  }
  for (int i=0; i<3; i++) 
    pthread_mutex_unlock(&s[i]); // free all waiting slaves
  return NULL;
}  


int main()
{ pthread_t t[4];

  XInitThreads();
  LCDPrintf("Multithreading\n");
  LCDMenu("THREAD 0", "THREAD 1", "THREAD 2", "END");
  
  pthread_mutex_init(&print, NULL);
  for (int i=0; i<3; i++)
  { pthread_mutex_init(&s[i], NULL);
    pthread_mutex_lock(&s[i]);
  }
  pthread_create(&t[0], NULL, slave, (void *) 0);
  pthread_create(&t[1], NULL, slave, (void *) 1);
  pthread_create(&t[2], NULL, slave, (void *) 2);
  pthread_create(&t[3], NULL, master,(void *) 3);

  pthread_exit(0);  // terminate program
}
