#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "watcom/thread.h"

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
int newfd = -1;

void *
thread(void *arg)
{
   int i;
   TID self;

pthread_mutex_lock(&mutex);
   printf("In thread 0x%8.8x:\n\n", _TLS);
   self = _TLS; //pthread_self();
   printf("    tid: 0x%8.8x\n", self); 
   printf("    pid: %d\n", self->pid); 
   printf("    stack pointer: 0x%8.8x\n", PTHREAD_STACK(self).ss_sp); 
   printf("    stack size: %d\n", PTHREAD_STACK(self).ss_size); 
   printf("    state: %d\n", self->state); 
   printf("    prio: %d\n", self->prio); 
   printf("    curprio: %d\n", self->curprio); 
pthread_mutex_unlock(&mutex);

   for (i = 0; i < 10; i++) {
      static char *str = "thread write\n";
      write(1, str, strlen(str));
   }

   pthread_mutex_lock(&mutex);
   while (newfd <= 1)
	pthread_cond_wait(&cv, &mutex);
   pthread_mutex_unlock(&mutex);

   {
      static char *str = "write to newfd\n";
      int len = strlen(str);
      write(newfd, str, len);
   }

   return NULL;
}

main()
{
   int args[2];
   int status;
   pthread_t child;
   int i;
   void *result;
   TID self;
   struct timespec when = { 1, 0 };

   args[0] = 0;
   args[1] = 0;

   if (pthread_create(&child, NULL, &thread, NULL) != EOK) {
	printf("Couldn't create child\n");
   }

pthread_mutex_lock(&mutex);
   printf("In main() (0x%8.8x):\n\n", _TLS);
   self = _TLS; //pthread_self();
   printf("    tid: 0x%8.8x\n", self); 
   printf("    pid: %d\n", self->pid); 
   printf("    stack pointer: 0x%8.8x\n", PTHREAD_STACK(self).ss_sp); 
   printf("    stack size: %d\n", PTHREAD_STACK(self).ss_size); 
   printf("    state: %d\n", self->state); 
   printf("    prio: %d\n", self->prio); 
   printf("    curprio: %d\n", self->curprio); 
pthread_mutex_unlock(&mutex);

   for (i = 0; i < 10; i++) {
      char *str = "main write\n";
      write(1, str, strlen(str));
   }

   newfd = dup(STDOUT_FILENO);
   if (newfd < 0) {
	fprintf(stderr, "unable to dup stdout\n: %s\n", strerror(errno));
	exit(0);
   }
   pthread_mutex_lock(&mutex);
   pthread_cond_signal(&cv);
   pthread_mutex_unlock(&mutex);

   sleep(1);
   status = (int)pthread_join(child, &result);
   sleep(10);
   exit(0);
}
