- 1、本文档共13页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
条件变量.doc
?条件变量 概述
条件变量提供 了另一个线程同步的方法,当mutex通过控制存取数据来实现线程同步时,条件变量允许线程基于实际的变量值来实现线程同步。
没有条件变量,开发者需要线程不停的轮询以查询条件是否满足,因为线程要不停的忙等,会消耗很多资源。条件变量就是不用轮询而能达到同样目的方法。
条件变量总是与mutex锁联系在一起。
下面是一个使用条件变量的代表性序列
Main Thread
o??????????????????????????????? 申明和初始化需要同步的全局数据/变量(比如:count)
o??????????????????????????????? 申明和初始化一个条件变量对象
o??????????????????????????????? 申明和初始化相关联的mutex
o??????????????????????????????? 创建threads A 和B并运行它们 Thread A
o??????????????????????????????? Do work up to the point where a certain condition must occur (such as count must reach a specified value)
o??????????????????????????????? Lock associated mutex and check value of a global variable
o??????????????????????????????? Call pthread_cond_wait() to perform a blocking wait for signal from Thread-B. Note that a call to pthread_cond_wait() automatically and atomically unlocks the associated mutex variable so that it can be used by Thread-B.
o??????????????????????????????? When signalled, wake up. Mutex is automatically and atomically locked.
o??????????????????????????????? Explicitly unlock mutex
o??????????????????????????????? Continue Thread B
o??????????????????????????????? Do work
o??????????????????????????????? Lock associated mutex
o??????????????????????????????? Change the value of the global variable that Thread-A is waiting upon.
o??????????????????????????????? Check value of the global Thread-A wait variable. If it fulfills the desired condition, signal Thread-A.
o??????????????????????????????? Unlock mutex.
o??????????????????????????????? Continue Main Thread
Join / Continue ?
条件变量 创建和销毁条件变量
函数:
pthread_cond_init (condition,attr)
pthread_cond_destroy (condition)
pthread_condattr_init (attr)
pthread_condattr_destroy (attr) 用法:
条件变量必须用pthread_cond_t 类型来声明,而且在使用之前必须初始化。在这里有两种方法初始化条件变量:
静态的方式初始化,例如: pthread_cond_t myconvar = PTHREAD_COND_INITIALIZER;
动态的方式,利用pthread_cond_init()进行初始化,被创建的条件变量ID通过condition 参数返回给调用线程。这种方法允许条件变量设置属性attr 。
可选的attr 用来设置条件变量属性,对于条件变量,这
文档评论(0)