如何正确离开临界区? [英] How to properly leave a Critical Section?

查看:86
本文介绍了如何正确离开临界区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下C ++代码,其中使用了关键部分对象

I have the following C++ code where I make use of the Critical Section object:

EnterCriticalSection(&cs);

// code that may throw an exception

LeaveCriticalSection(&cs);

如何确保 LeaveCriticalSection 函数

推荐答案

只需编写一个使用析构函数进行清理的防护:

Just write a guard utilizing the destructor for clean up:

struct Guard {
  CriticalSection& cs;
  Guard(CriticalSection& cs)
  : cs(cs)
  {
    EnterCriticalSection(cs);
  }
  ~Guard() {
    LeaveCriticalSection(cs);
  }
  Guard(const Guard&) = delete;  
  Guard& operator = (const Guard&) = delete;
};

用法:

void f() {
   Guard guard(cs);
   ...
}

这篇关于如何正确离开临界区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆