信号量和 sem_wait() 的问题

发布于 2024-08-26 20:26:42 字数 1007 浏览 7 评论 0原文

我有一个由多个 pthreads 使用的队列结构。如果队列不为空,线程应该从队列中出列,然后执行任务。

我最初将其设置为 while 循环,其中线程使用 mutex_lock 检查队列是否为空。不幸的是,这使我的程序变得缓慢。

我尝试实现一个信号量作为队列的“计数”变量,但不幸的是,当我尝试调用 sem_wait() 时,我遇到了段错误。我发现 gdb 和 semaphore.h 不能很好地协同工作,所以我真的很茫然。我可能会犯一个新手错误,所以任何帮助或建议将不胜感激。

队列结构:

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

这是它的初始化:

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);

}

我确保

   queue *q;
    q = CreateQueue();

在创建任何线程之前调用:。

这是 seg 错误的调用,

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 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终陌 2024-09-02 20:26:42

如果上面示例中的 CreateQueue 已完成,那么它似乎没有设置全局 q 变量。它将结果分配给局部变量。但它似乎没有返回变量。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文