CRITICAL_SECTION 和 CCriticalSection 之间的关系是什么

发布于 2024-08-02 20:35:32 字数 281 浏览 4 评论 0原文

CRITICAL_SECTION 和 CCriticalSection 之间的关系是什么? CCriticalSection 是 CRITICAL_SECTION 的包装吗?

顺便说一句:

我认为下面的代码没有意义,因为 cs 不是全局的,它每次在 lock() 之前都会初始化,所以它不能锁定 XXX ,是吗?

int func
{
CCriticalSection cs;
cs.Lock();
XXX
cs.Unlock();
}

非常感谢!

What is the relation ship between CRITICAL_SECTION and CCriticalSection.
is CCriticalSection a wrapper of CRITICAL_SECTION?

BTW:

I think the following code is meanless because the cs is not Global, it initial every times before lock() so it can't lock the XXX , is it ?

int func
{
CCriticalSection cs;
cs.Lock();
XXX
cs.Unlock();
}

Many Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

诺曦 2024-08-09 20:35:32

是的,MFC CCriticalSection 部分只是一个包装器围绕 Win32 CRITICAL_SECTION。

这几乎适用于所有 MFC,它是围绕标准 Win32 功能的大量包装类。

至于您的代码示例,是的,在该上下文中使用关键部分是没有意义的。临界区的作用类似于命名互斥体,它确保资源一次只能由单个线程访问。临界区的正确使用方式是作为一个可由多个线程访问的对象,然后当使用一次不能被多个线程使用的资源时:

MyGlobalCS.Lock();

// Do important work on resource

MyGlobalCS.Unlock();

另请注意,如果很难将临界区放入共享位置,则可以使用命名的 互斥体 代替。

Yes the MFC CCriticalSection section is just a wrapper around a Win32 CRITICAL_SECTION.

This goes for pretty much all of MFC, its a huge set of wrapper classes around standard Win32 functionality.

As to your code example, yes the use of a critical section in that context is meaningless. What a critical section does is akin to a named mutex, it ensures that a resource can only be accessed by a single thread at a time. Proper use of a critical section would be as an object accessible by multiple threads, then when using a resource which cannot be used by more than one thread at a time:

MyGlobalCS.Lock();

// Do important work on resource

MyGlobalCS.Unlock();

Also note that if its hard to get the critical section into a shared location you can use a named mutex instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文