开发者

Problem with semaphores and sem_wait()

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 t开发者_StackOverflow社区o 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜