ajax_velu
ajax_velu

Reputation: 296

Segmentation Fault on multithreaded Producer Consumer C Program

// This is the multi-threaded code for a producer Consumer program ,it runs //successfully completion of both the threads , but receives a Segmentation error just //before thread join , I am not really able to figure it out

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

void* writer_function ();
void* reader_function ();
char buffer[9];

sem_t empty_buffers;
sem_t full_buffers;

int main()
{
 pthread_t thread1, thread2;
 //const char *message1 = "Thread 1";
 //const char *message2 = "Thread 2";
 int  iret1, iret2;

 sem_init(&empty_buffers,0,8);
 sem_init(&full_buffers,0,0);

/* Create independent threads each of which will execute function */

 iret1 = pthread_create( &thread1, NULL,writer_function, NULL);
 if(iret1)
 {
     fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
     exit(EXIT_FAILURE);
 }

 iret2 = pthread_create( &thread2, NULL, reader_function(), NULL);
 if(iret2)
 {
     fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
     exit(EXIT_FAILURE);
 }

 // Runs Successfully ,and segmentation fault here  
 pthread_join( thread1, NULL);
 pthread_join( thread2, NULL);

 printf("pthread_create() for thread 1 returns: %d\n",iret1);
 printf("pthread_create() for thread 2 returns: %d\n",iret2);

 sem_destroy(&empty_buffers);
 sem_destroy(&full_buffers);

 /* Wait till threads are complete before main continues. Unless we  */
 /* wait we run the risk of executing an exit which will terminate   */
 /* the process and all threads before the threads have completed.   */


 printf("This marks the end and the threads to be joined \n ");
 //exit(EXIT_SUCCESS);
 return 0;

}

void* writer_function ()
{
     int i ;
     for (i = 0 ; i < 40 ; i++){
        char c = (i + 66);
        sem_wait(&empty_buffers);
        buffer[i%8] = c;
        sem_post(&full_buffers);
        printf("  WRITER:the letter Written is %c\n", c);
     }
}

void* reader_function ()
{
     int i ;
     for (i = 0 ; i < 40 ; i++){
        sem_wait(&full_buffers);
        char c = buffer[i%8];
        sem_post(&empty_buffers);
        printf("READER:the letter Received is %c\n", c);
     }
}

Upvotes: 0

Views: 257

Answers (1)

jaroslawj
jaroslawj

Reputation: 462

change:

iret2 = pthread_create( &thread2, NULL, reader_function(), NULL);

to

iret2 = pthread_create( &thread2, NULL, reader_function, NULL);

add return NULL; for both functions reader_function, writer_function after loop and change their header from writer_/reader_function() to writer_/reader_function(void *args)

Upvotes: 1

Related Questions