Win32读/写锁仅使用关键部分 [英] Win32 Read/Write Lock Using Only Critical Sections

查看:116
本文介绍了Win32读/写锁仅使用关键部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在工作中使用Win32 api作为项目的一部分在C ++中实现读/写锁定。所有现有的解决方案都使用在执行期间需要上下文切换的内核对象(信号量和互斥体)。这对我的应用程序来说太慢了。

I have to implement a read/write lock in C++ using the Win32 api as part of a project at work. All of the existing solutions use kernel objects (semaphores and mutexes) that require a context switch during execution. This is far too slow for my application.

如果可能的话,我想只使用关键部分实现一个。锁不必是过程安全的,只有线程安全。

I would like implement one using only critical sections, if possible. The lock does not have to be process safe, only threadsafe. Any ideas on how to go about this?

推荐答案

我不认为这样做不需要使用至少一个内核 - (Mutex或Semaphore),因为你需要内核的帮助,使调用进程阻塞,直到锁可用。

I don't think this can be done without using at least one kernel-level object (Mutex or Semaphore), because you need the help of the kernel to make the calling process block until the lock is available.

关键部分提供阻塞,但是API太有限了。例如你不能抓住一个CS,发现读锁可用,但不是一个写锁,并等待其他进程完成阅读(因为如果其他进程有关键部分,它将阻止其他读者是错误的,如果它然后你的进程不会阻塞,但旋转,燃烧CPU周期。)

Critical sections do provide blocking, but the API is too limited. e.g. you cannot grab a CS, discover that a read lock is available but not a write lock, and wait for the other process to finish reading (because if the other process has the critical section it will block other readers which is wrong, and if it doesn't then your process will not block but spin, burning CPU cycles.)

但是你可以做的是使用自旋锁和回退到互斥是争论。关键部分本身以这种方式实现。我将采取现有的关键部分实现,并用独立的读取器&作家计数。

However what you can do is use a spin lock and fall back to a mutex whenever there is contention. The critical section is itself implemented this way. I would take an existing critical section implementation and replace the PID field with separate reader & writer counts.

这篇关于Win32读/写锁仅使用关键部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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