/*
  PLOVER: RACE, BUFF.OVER
 */

/*
  unlocked shared resource
*/

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFSIZE 5

pthread_mutex_t mut  = PTHREAD_MUTEX_INITIALIZER;

char *shortstr(char *p, int n, int targ)
{
	if(n > targ)
		return shortstr(p+1, n-1, targ);
	return p;
}



void *foo(void* targ)
{

  char *buffer = ((char **)targ)[0];
  char *str =  ((char **)targ)[1];
  char *str2;


  str2 = shortstr(str, strlen(str), BUFSIZE-1);
  strcpy(buffer, str2);
  printf("result: %s\n", buffer);

  
  pthread_exit(NULL);
}

void *bar(void* targ)
{
  char **buffer = (char **)targ;
  pthread_mutex_lock(&mut);
  *buffer = NULL;
  pthread_mutex_unlock(&mut);
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  char buf[BUFSIZE];
  pthread_t tids[2];
  char *tin[2];
  tin[0] = buf;
  if(argc > 1)
    tin[1] = argv[1];
  else
    return 0;

  int rc = pthread_create(&tids[0], NULL, foo, (void *)tin);
  rc = pthread_create(&tids[1], NULL, bar, (void *)&buf);
  pthread_join(tids[0],NULL);
  pthread_join(tids[1],NULL);

  printf("final string: %s \n", buf);

  return 0;
}
