/* file:    threads.c
 * author:  Albert Huang
 * date:    23 January 2002
 *
 * simple example of how to use threads.
 * This program creates two threads.  One thread messes with the
 * motors while the other thread messes with the LCD
 * After 5 seconds, the parent thread kills both children and exits
 */

#include <unistd.h>
#include <dmotor.h>
#include <conio.h>

/*
 * starting point for the first thread
 * All this thread does is spin the motors
 */
int thread_one(int argc, char *argv[])
{
  motor_a_dir(fwd);
  motor_b_dir(fwd);
  motor_c_dir(fwd);

  motor_a_speed(MAX_SPEED / 2);
  motor_b_speed(MAX_SPEED / 2);
  motor_c_speed(MAX_SPEED / 2);

  while(1)
    {
      /* alternate motor directions */
      motor_a_dir(fwd);
      motor_b_dir(fwd);
      motor_c_dir(fwd);
      msleep(500);

      motor_a_dir(rev);
      motor_b_dir(rev);
      motor_c_dir(rev);
      msleep(500);

      /* now repeat */
    }
}

/*
 * starting point for the second thread
 * all this thread does is flash messages on the LCD
 */
int thread_two(int argc, char *argv[])
{
  char *string1 = "Hello";
  char *string2 = "World";

  while (1)
    {
      cputs(string1);
      msleep(750);

      cputs(string2);
      msleep(750);

      cls();
      msleep(500);
    }

}


int main(int argc, char *argv[])
{
  pid_t thread1, thread2;

  /* start the two children threads going */
  thread1=execi(&thread_one, 0, 0, PRIO_NORMAL, DEFAULT_STACK_SIZE);
  thread2=execi(&thread_two, 0, 0, PRIO_NORMAL, DEFAULT_STACK_SIZE);

  /* go to sleep for 5 seconds */
  msleep(5000);

  /* now kill the kids */
  kill (thread1);
  kill (thread2);

  /* cleanup */
  motor_a_speed(MIN_SPEED);
  motor_b_speed(MIN_SPEED);
  motor_c_speed(MIN_SPEED);
  motor_a_dir(off);
  motor_b_dir(off);
  motor_c_dir(off);
  cls();

  return 0;
}
