栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Linux下AutoResetEvent的C ++等效项是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux下AutoResetEvent的C ++等效项是什么?

AutoResetEvent最类似于二进制信号量。人们说“条件变量”本身并没有错,但是条件变量用于类似的情况,而不是类似的对象。您可以在条件变量之上实现一个(未命名的)AutoResetEvent:

#include <pthread.h>#include <stdio.h>class AutoResetEvent{  public:  explicit AutoResetEvent(bool initial = false);  ~AutoResetEvent();  void Set();  void Reset();  bool WaitOne();  private:  AutoResetEvent(const AutoResetEvent&);  AutoResetEvent& operator=(const AutoResetEvent&); // non-copyable  bool flag_;  pthread_mutex_t protect_;  pthread_cond_t signal_;};AutoResetEvent::AutoResetEvent(bool initial): flag_(initial){  pthread_mutex_init(&protect_, NULL);  pthread_cond_init(&signal_, NULL);}void AutoResetEvent::Set(){  pthread_mutex_lock(&protect_);  flag_ = true;  pthread_mutex_unlock(&protect_);  pthread_cond_signal(&signal_);}void AutoResetEvent::Reset(){  pthread_mutex_lock(&protect_);  flag_ = false;  pthread_mutex_unlock(&protect_);}bool AutoResetEvent::WaitOne(){  pthread_mutex_lock(&protect_);  while( !flag_ ) // prevent spurious wakeups from doing harm    pthread_cond_wait(&signal_, &protect_);  flag_ = false; // waiting resets the flag  pthread_mutex_unlock(&protect_);  return true;}AutoResetEvent::~AutoResetEvent(){  pthread_mutex_destroy(&protect_);  pthread_cond_destroy(&signal_);}AutoResetEvent event;void *otherthread(void *){  event.WaitOne();  printf("Hello from other thread!n");  return NULL;}int main(){  pthread_t h;  pthread_create(&h, NULL, &otherthread, NULL);  printf("Hello from the first threadn");  event.Set();  pthread_join(h, NULL);  return 0;}

但是,如果您需要命名的自动重置事件,则可能需要查看信号量,并且可能很难翻译代码。无论哪种方式,我都会仔细查看平台上pthread的文档,条件变量和自动重置事件并不相同,并且行为也不相同。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/381204.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号