I'm developing a basic multi-threaded application, I have never worked with threads and semaphores before. The main program calls thread1 to read input from standard input, every time input is entered that thread than calls thread2 to process it. Than thread2 calls the thread3 to display the results. Thread1 must wait until thread2 and thread3 are done. Thread 1 also needs to be able to tell the other threads to shut down on system exit. I was thinking of using semaphores to implement synchronization since the threads will always run in that order, 1,2,3. Can anyone help me out, this is what i have so far. Any links to implementing semaphores would be great too.
p.s. other threads haven't been implemented yet
Code:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
//Macro
#define NUM_THREADS 3
#define BUFFSIZE 81
//Type
typedef enum { FALSE, TRUE } boolean;
//Function prototypes
void *input( void *id );
//Globals (shared data)
char *operator1;
int operand1, operand2, result;
int main( int argc, char *argv[] )
{
pthread_t threads[ NUM_THREADS ];
int ret_code;
long id = 1;
ret_code = pthread_create( &threads[0], NULL, input, (void *)id );
if( ret_code )
{
printf( "\nERROR! Could not create thread, error code %d returned", ret_code );
exit(-1);
}
pthread_exit( NULL );
}
void *input( void *id )
{
char buffer[ BUFFSIZE ]; // room for 80 chars plus \0
char *input;
printf( "$>" );
input = fgets( buffer, BUFFSIZE, stdin ); //read input from console
//Keep getting input from console until a string contains the letter
//q upper or lower case
while( input != NULL && strstr( input, "q" ) == NULL && strstr( input, "Q" ) == NULL )
{
//Format of string will be error free and
//in the format 'operand operator operand'
//convert operand's to integers
operand1 = atoi( strtok( input, " " ) ); //write first operand to shared data
operator1 = strtok( NULL, " " ); //write operator to shared data
operand2 = atoi( strtok( NULL, " " ) ); //write second operand to shared data
//Signal thread2 to start processing, than wait until thread3
//has finished so we can restart the entire process again
//Next line
printf( "$>" );
input = fgets( buffer, BUFFSIZE, stdin );
}
//Quit command entered, signal other threads to exit and shut down
pthread_exit( NULL );
}
I'm not 100% sure if I should create the other threads within the 'main' program or not, I guess I have to, but block them and allow thread1 to unblock them?