pthread_cond_wait 不阻塞?

gongpengrong 2012-07-02 07:23:52
请教为什么下面的程序,在pthread_cond_wait这不阻塞呢。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include<errno.h>


// 读写互斥体
pthread_mutex_t mutexWriteRead = PTHREAD_MUTEX_INITIALIZER;
// 读条件变量
pthread_cond_t condWrote = PTHREAD_COND_INITIALIZER;


int main(int args, const char *argc[])
{
// 如果 要写位置是待读位置 的话,则
int dwRet =0;
do
{
pthread_mutex_lock( &mutexWriteRead );
dwRet=pthread_cond_wait(&condWrote, &mutexWriteRead ); //应当阻塞在此,但没有
if( EINVAL == dwRet )
{
printf("== EINVAL\n");
}
else
{
printf("end wait %d\n",dwRet);
}
}
while(1);
}

在ubuntu上运行此程序,结果如下:pthread_cond_waint根本没有阻塞,它的返回值为0说明它是接收到了信号,但这个信号从什么地方来的呢。
end wait 0
end wait 0
end wait 0
end wait 0
...


...全文
345 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
happylifer 2012-07-03
  • 打赏
  • 举报
回复
一般都是要这么用的:

pthread_mutex_lock(&m);
while(!wait_condition)
pthread_cond_wait(&v, &m);
pthread_mutex_unlock(&m);

只有这样才保险,因为有时候是虚假返回。
happylifer 2012-07-03
  • 打赏
  • 举报
回复
一般都是要这么用的:

pthread_mutex_lock(&m);
while(!wait_condition)
pthread_cond_wait(&v, &m);
pthread_mutex_unlock(&m);

只有这样才保险,因为有时候是虚假返回。
qq120848369 2012-07-02
  • 打赏
  • 举报
回复
没听说过这个道理, 我这里都正常阻塞/
gongpengrong 2012-07-02
  • 打赏
  • 举报
回复
pthread_cond_wait是用于多线程之间的同步,如果仅一个主线程,我试的结果是根本不会阻塞,但只要增加一个线程就会阻塞。我不太明白这个是什么原因,希望高手指点一下。
acaicaia 2012-07-02
  • 打赏
  • 举报
回复
楼主可以先用pthread_create创建一个线程,然后在线程的处理函数中调用pthread_cond_wait看看。
qq120848369 2012-07-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

我明白了,这个是用于多线程的。
[/Quote]

不要牵强的明白。。。汗。。

Upon successful completion, a value of zero shall be returned; otherwise, an error number shall be returned to indicate the error.

返回0表明成功了。


Ubuntu怎么总是很怪异,程序没有问题应该阻塞的。
gongpengrong 2012-07-02
  • 打赏
  • 举报
回复
我明白了,这个是用于多线程的。

23,116

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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