免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3596 | 回复: 2
打印 上一主题 下一主题

pthread_cond_signal发送信号时并不需要占有互斥量? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-09-01 20:19 |只看该作者 |倒序浏览
在man pthread_cond_signal里面看到这样一句话:

It  is  not  safe to use the pthread_cond_signal() function in a signal handler that is invoked asynchronously. Even if it
       were safe, there would still be a race between the test of the Boolean pthread_cond_wait() that could not  be  efficiently
       eliminated.

看的迷迷乎乎,是不是说pthread_cond_signal不能在异步调用的信号处理程序 使用?
否则就会出现竞争?
与pthread_cond_wait()???

我想不太明白……

如果有多个线程用pthread_cond_signal向一个条件变量发送信号,是不是也会出现竞争?

谢谢!!!

论坛徽章:
0
2 [报告]
发表于 2009-09-01 22:16 |只看该作者
首先这样的代码不安全, 因为线程有可能被signal打断,这样就会锁死。
in signal
   mutex_lock(&m);
   ....
   mutex_unlock(&m);

in thread
   mutex_lock(&m);
   ....
   mutex_unlock(&m);

然而condition很难实现的那么单纯,不排除上述类似mutex的情况,锁死就很可能了。
这是boost 1.33中的condition signal的实现,里面也有mutex lock.

  1. void condition_impl::notify_one()
  2. {
  3.     unsigned signals = 0;

  4.     int res = 0;
  5.     res = WaitForSingleObject(reinterpret_cast<HANDLE>(m_mutex), INFINITE);
  6.     assert(res == WAIT_OBJECT_0);

  7.     if (m_waiting != 0) // the m_gate is already closed
  8.     {
  9.         if (m_blocked == 0)
  10.         {
  11.             res = ReleaseMutex(reinterpret_cast<HANDLE>(m_mutex));
  12.             assert(res);
  13.             return;
  14.         }

  15.         ++m_waiting;
  16.         --m_blocked;
  17.         signals = 1;
  18.     }
  19.     else
  20.     {
  21.         res = WaitForSingleObject(reinterpret_cast<HANDLE>(m_gate), INFINITE);
  22.         assert(res == WAIT_OBJECT_0);
  23.         if (m_blocked > m_gone)
  24.         {
  25.             if (m_gone != 0)
  26.             {
  27.                 m_blocked -= m_gone;
  28.                 m_gone = 0;
  29.             }
  30.             signals = m_waiting = 1;
  31.             --m_blocked;
  32.         }
  33.         else
  34.         {
  35.             res = ReleaseSemaphore(reinterpret_cast<HANDLE>(m_gate), 1, 0);
  36.             assert(res);
  37.         }
  38.     }

  39.     res = ReleaseMutex(reinterpret_cast<HANDLE>(m_mutex));
  40.     assert(res);

  41.     if (signals)
  42.     {
  43.         res = ReleaseSemaphore(reinterpret_cast<HANDLE>(m_queue), signals, 0);
  44.         assert(res);
  45.     }
  46. }

复制代码

论坛徽章:
0
3 [报告]
发表于 2010-07-16 23:57 |只看该作者
顶一下,大家讨论一下
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP