信号量和 sem_wait() 的问题
我有一个由多个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果上面示例中的 CreateQueue 已完成,那么它似乎没有设置全局
q
变量。它将结果分配给局部变量。但它似乎没有返回变量。If
CreateQueue
in the above example is complete, then it does not seem to be setting your globalq
variable. It assigns the results to a local variable. But it does not seem to return the variable.