免费注册 查看新帖 |

Chinaunix

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

线程同步:使用信号和条件变量有什么区别?哪个更有优势? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-08-13 15:56 |只看该作者 |倒序浏览
有信号量为什么还要搞条件变量呢?

论坛徽章:
0
2 [报告]
发表于 2010-08-13 22:11 |只看该作者
回复 1# gqbfree


    是nachos实验里面的condition variable吧,故名思议有是基于某个条件的,可能是使用上的方便吧,另外理论基础上,条件变量貌似用了操作系统书上讲互斥时候的管程有关,实现技术手段不同。

论坛徽章:
0
3 [报告]
发表于 2010-08-13 22:44 |只看该作者
条件变量通过允许线程阻塞和等待另一个线程发送信号的方法弥补了互斥锁的不足,它常和互斥锁一起使用。

论坛徽章:
0
4 [报告]
发表于 2010-08-16 09:23 |只看该作者
回复 3# linux初学三月

既然两种方式都可以实现同步,那么为什么要两种?分别在什么场景下使用?    信号量和条件变量

论坛徽章:
0
5 [报告]
发表于 2010-08-16 09:24 |只看该作者
回复 3# linux初学三月

信号量也可以阻塞啊? 跟互斥锁没关系

论坛徽章:
0
6 [报告]
发表于 2010-08-16 11:25 |只看该作者
本帖最后由 Solaris12 于 2010-08-16 11:34 编辑
有信号量为什么还要搞条件变量呢?
gqbfree 发表于 2010-08-13 15:56



   

信号量是可以和条件变量互换使用的.

但在不同的场合,用对了写出的代码更简洁.

例如.Solaris文件系统里大量使用信号量的设计,一开始我是不理解的,觉得用条件变量也一样,现在发现信号量在生产者需要等待消费者而无条件睡眠的情况下,用信号量是最简单高效。



我一直觉得SUN的图书Multithreaded Programming Guide是多线程编程的经典之作。

刚才大概看了看你的文档,  你关于Semaphore的文字大概可以用这本书的章节作为答案



http://docs.sun.com/app/docs/doc/816-5137/sync-11157?a=view

The two basic sorts of semaphores are binary semaphores and counting
semaphores. Binary semaphores never take on values other than zero or
one, and counting semaphores take on arbitrary nonnegative values. A
binary semaphore is logically just like a mutex.

However, although not always enforced, mutexes should be unlocked only
by the thread that holds the lock. Because no notion exists of “the
thread that holds the semaphore,” any thread can perform a V or
sem_post (3RT) operation.

Counting semaphores are nearly as powerful as conditional variables
when used in conjunction with mutexes. In many cases, the code might
be simpler when implemented with counting semaphores rather than with
condition variables, as shown in Example 4–14, Example 4–15, and
Example 4–16.

论坛徽章:
0
7 [报告]
发表于 2010-08-16 15:07 |只看该作者
回复 6# Solaris12

    非常感谢楼上的兄弟,辛苦。

   还是有些奇怪,难道仅仅是代码简单易看的区别? 英语理解应该没错吧。 那我觉得条件变量没有存在的必要了。

However, when a mutex is used with condition variables, an implied bracketing is present. The bracketing clearly delineates which part of the program is being protected. This behavior is not necessarily the case for a semaphore, which might be called the go to of concurrent programming. A semaphore is powerful but too easy to use in an unstructured, indeterminate way.

论坛徽章:
0
8 [报告]
发表于 2010-08-17 12:39 |只看该作者
信号量只能阻塞一个,而且可能丢失
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP