/* Project 1 - problem 6 Program to implement Posix threads. One thread should perform addition while the other thread should subtract 
from the result of addition, another number*/


#include <pthread.h>
#include <stdio.h>
#include <string.h>
//#include <sys/stat.h>
//#include <sys/types.h>
# include <stdlib.h>
# include <unistd.h>


void* ADD(void *arg)
{
     printf("\n in thread 2");
     int A = *((int *)(arg));
     int B = *((int *)(arg) + 1);

     return ((void *)(A+B));
}

int SUBTRACT(int r,int C)
{
    
     return (r-C);
}     
int main(int argc,char *argv[])
{
    int i;
    int arg_for_thr2[2];
    int A,B,C;
    int result;
    int error;
   void  *temp;
    pthread_t tid;
    pthread_attr_t attr;
    
    
         if(argc!=4){
                   fprintf(stderr,"\n ERROR ; CORRECT USAGE:Thread ARG1,ARG2,ARG3\n");  /* check for valid number of command-line arguments */
                   return 1;
         }
         
    A=atoi(argv[1]);
    B=atoi(argv[2]);
    C=atoi(argv[3]);
    
    arg_for_thr2[0]=A;
    arg_for_thr2[1]=B;
    
   pthread_attr_init(&attr);
  pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    
     pthread_create(&tid, &attr, ADD, arg_for_thr2);
    /*  printf( "Failed to create thread:%s \n",strerror(error) );
      return 1;
      }
      */
      if (error = pthread_join(tid, &temp)){
          fprintf(stderr, "Failed to join thread:%s \n",strerror(error) );
           return 1;
           }    

      result=SUBTRACT(*(int *)temp,C);
      fprintf(stderr,"Result is  %d\n",C);
      
      return 0;
}    
