简体   繁体   English

线程读取与写入锁定

[英]Thread read versus write locking

I'm writing a CPU intensive program in C++ that has several threads needing to access a shared data structure, so locking will be required. 我正在用C ++写一个CPU密集型程序,该程序有多个线程需要访问共享数据结构,因此将需要锁定。 To maximize throughput, I want to keep the bottleneck to a minimum. 为了最大程度地提高吞吐量,我想将瓶颈降到最低。 It looks like maybe nine times out of ten it will only be necessary to read the data structure, and one time out of ten it will be necessary to modify it. 看起来十分之九可能只需要读取数据结构,而十分之一就有必要对其进行修改。

Is there a way to have threads take read or write locks, so that write locks block everything but read locks don't block each other? 有没有一种方法可以让线程获取读或写锁,以便写锁可以阻止所有内容,但读锁不能互相阻止?

A portable solution would be ideal, but if there is one solution for Windows and another for Linux that would be okay. 便携式解决方案将是理想的选择,但是如果有一种针对Windows的解决方案,而另一种针对Linux的解决方案则可以。

Yes, this is a common situation that can be solved with a reader-writer lock . 是的,这是一种常见的情况,可以使用读写器锁解决。

Note that depending on the dynamic properties of your program, you may need to be careful about writer starvation . 请注意,根据程序的动态属性,您可能需要注意作家饥饿 If there are enough readers that their attempts to read always overlap (or overlap for a long time), then a simple implementation of a reader-writer lock will "starve" the writer by making the writer wait until there are no readers reading. 如果有足够多的读者认为他们的阅读尝试总是重叠(或长时间重叠),那么简单的读者-作家锁定实现将通过使作家等待直到没有读者阅读来“饿死”作家。 In a more advanced implementation, a writer request will be conceptually inserted into the queue before subsequent readers, allowing the writer to have a chance to access after all the previously active readers finish. 在更高级的实现中,将在以后的读取器之前将写入器请求概念性地插入队列,从而使写入器有机会在所有先前活动的读取器完成后进行访问。

Most implementations require you to know ahead of time whether you want a read lock or a write lock. 大多数实现要求您提前知道是要读锁还是写锁。 Some implementations allow you to "upgrade" a read lock into a write lock without having to release the read lock first (which would give another writer an opportunity to enter the lock). 一些实现使您可以将读取锁“升级”到写入锁,而不必先释放读取锁(这将使另一个写入者有机会进入该锁)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM