关于pthread_cond_wait

newarr 2008-12-07 10:15:36
在看Unix编程关于多线程的内容,看到pthread_cond_wait觉得很费解,为何在锁定数据队列的时候等待?那写进程不是完全没机会解锁来往队列里写东西释放该等待队列?还有个问题就是pthread_cond_wait时,该进程时什么状态,是休眠吗?下面是代码。
#include <pthread.h>
#include <unistd.h>

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

struct node {
int n_number;
struct node *n_next;
} *head = NULL;

/*[thread_func]*/
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread.\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}

static void *thread_func(void *arg)
{
struct node *p = NULL;

pthread_cleanup_push(cleanup_handler, p);
while (1) {
pthread_mutex_lock(&mtx);
while (head == NULL)
pthread_cond_wait(&cond, &mtx);
p = head;
head = head->n_next;
printf("Got %d from front of queue\n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;

/*EC_CLEANUP_BGN
(void)pthread_mutex_unlock(&mtx);
EC_FLUSH("thread_func")
return 1;
EC_CLEANUP_END*/
}
/*[]*/

int main(void)
{
pthread_t tid;
int i;
struct node *p;

pthread_create(&tid, NULL, thread_func, NULL);
/*[tx6-main]*/
for (i = 0; i < 10; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the line.So cancel thread 2.\n");
pthread_cancel(tid);
pthread_join(tid, NULL);
printf("All done -- exiting\n");
return 0;
/*[]*/

/*EC_CLEANUP_BGN
return EXIT_FAILURE;
EC_CLEANUP_END*/
}
...全文
617 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
此外:
while (head == NULL)
pthread_cond_wait(&cond, &mtx);
这里用了while (head == NULL) 就是为了防止pthread_cond_wait被其他中断信号唤醒(如SIGINT)而队列里没有可读资源,这样该线程就会再次进入wait,如果是if(head == NULL) ,那一旦该进程被以外唤醒后,便会不停地循环运行,从而pthread_cond_wait的机制就失效了。
http://topic.csdn.net/t/20060706/11/4863663.html
这里有个帖你也可以参考一下。
wuyu637 2008-12-07
  • 打赏
  • 举报
回复
extern int pthread_cond_wait __P ((pthread_cond_t *__cond,pthread_mutex_t *__mutex));

   调用这个函数时,线程解开mutex指向的锁并被条件变量cond阻塞。线程可以被函数pthread_cond_signal和函数 pthread_cond_broadcast唤醒线程被唤醒后,它将重新检查判断条件是否满足,如果还不满足,一般说来线程应该仍阻塞在这里,被等待被下 一次唤醒。这个过程一般用while语句实现。
  • 打赏
  • 举报
回复
pthread_cond_wait会先解除该锁定,然后再等待信号再进入休眠,直到再次被唤醒(大多数情况下是等待的条件成立而被唤醒,唤醒后,该进程会先锁定先前队列,再读取资源。所以,你不用担心资源被死锁。

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧