views:

206

answers:

1

I have a queue structure that is being used by several pthreads. The threads are supposed to dequeue from the queue if it's not empty and then do their business.

I initially had this set up as a while loop where the threads checked whether the queue was empty using a mutex_lock. Unfortunately this slowed my program down to a crawl.

I tried to implement a semaphore as the "count" variable of my queue, but unfortunately I'm running into a segfault when I try and call sem_wait(). I've found the gdb and semaphore.h don't play well together, so I'm really at a loss. I may be making a novice mistake, so any help or suggestions would be appreciated.

Queue structure:

typedef struct {
  int q[QUEUESIZE+1];
  int first;
  int last;
  sem_t count;
} queue;

Here is the initialization of it:

queue *CreateQueue(void)
{
  queue *q;
  q = (queue*)malloc(sizeof(queue));
  if (q == NULL)
    return NULL;
  q->first = 0;
  q->last = 0;
  sem_init(&(q->count),0, 0);

}

And I make sure that I call:

   queue *q;
    q = CreateQueue();

before any threads are created.

Here is the call that seg faults

void *ThreadWait(void *t) {
  while(1) {
    sem_wait(&(q->count));  //THIS SEGFAULTS
    ThreadFun(); //this is the function the thread would go to to do all the work
  }
}

I'm hoping this is just a simple mistake on my part that I can't see right now.

Thanks in advance.

EDIT: to add some clarifying code

+2  A: 

If CreateQueue in the above example is complete, then it does not seem to be setting your global q variable. It assigns the results to a local variable. But it does not seem to return the variable.

Mark Wilkins
You are a miracle worker. I just noticed that it didn't return a value. Another reason to compile with -Wall. Thanks!
Evan
+1 good catch, always check the basics first :)
Nikolai N Fetissov