[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

pthreads, semaphores and segmentation fault



Hi All!

I was wrting a small test program using semaphores and pthreads. The
program compiles fine with  'g++ -lpthread -o a8 a8.cpp'

But when I run it, I get: segmentation fault. If I comment out the
second pthread_join() and compile and run it, then I get the output on
the screen and no segmentation fault.

If I run it in gdb, I get:
(gdb) run
Starting program: a8
[Thread debugging using libthread_db enabled]
[New Thread 0x7fda52cbd6f0 (LWP 14657)]
[New Thread 0x41357950 (LWP 14660)]
Entered producer thread
[New Thread 0x41b58950 (LWP 14661)]
Entered consumer thread
[Thread 0x41b58950 (LWP 14661) exited]
[Thread 0x41357950 (LWP 14660) exited]

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fda52cbd6f0 (LWP 14657)]
0x00007fda528a8628 in pthread_join () from /lib/libpthread.so.0
(gdb)

The program is listed below. Can anyone tell me if I am doing something wrong.

All this is done on Debian Lenny amd64 port.


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

class mailbox {
 public:
  mailbox();  //constructor
  int request();  //return next int from mailbox or block
  void release(int x);  //add x to mailbox or block

 private:
  sem_t num_empty;
  sem_t num_full;
  int *data;
  int producer_ptr;
  int consumer_ptr;

};

mailbox::mailbox()
{
  sem_init(&num_empty, 0, 10);
  sem_init(&num_full, 0, 0);
  data = (int *)malloc(10);
  producer_ptr = 0;
  consumer_ptr = 0;
}

int mailbox::request()
{
  sem_wait(&num_full);

  int temp = data[consumer_ptr];
  sem_post(&num_empty);
  consumer_ptr = (consumer_ptr + 1) % 10;

  return temp;
}

void mailbox::release(int x)
{
  sem_wait(&num_empty);

  data[producer_ptr] = x;
  sem_post(&num_full);
  producer_ptr = (producer_ptr + 1) % 10;
}

mailbox m;  //declares m to be a mailbox of integers of size 10

void *producer(void *arg)
{

  printf("Entered producer thread\n");

  int j;
  for (j = 0; j < 105; j++)
    m.release(j);

  pthread_exit(NULL);
}

void *consumer(void *arg)
{

  printf("Entered consumer thread\n");

  int j;
  for (j = 0; j < 100; j++)
    printf(" %d ", m.request());

  pthread_exit(NULL);
}

int main()
{
  pthread_t TId1, TId2;

  pthread_create(&TId1, NULL, producer, NULL);
  pthread_create(&TId1, NULL, consumer, NULL);

  pthread_join(TId1, NULL);
  pthread_join(TId2, NULL);

  printf("\n\n\n");

  return 0;
}





-- 
Sincerely yours,
Alexandru Cardaniuc


Reply to: