写入时同步锁?读?或者两者都有?

发布于 2024-10-10 14:47:55 字数 305 浏览 7 评论 0原文

假设我有一个字节数组,Private Data as Byte()。该数组在类中是私有的。该类提供了用于读取和写入Data 的公共函数。

这个类可以被多个线程访问,所以我想避免读取和写入不同时发生的情况。

目前,我使用 SyncLock 来避免出现问题。我可以将 SyncLock Data 仅放入写入函数中,还是需要放入读取函数中?或者,两者都有?

我心里没有具体的代码示例。我只是好奇,如果写入函数的 SyncLock 将使写入首先具有对其的独占访问权,那么锁定读取和写入函数是否有任何好处。

Suppose I have a byte array, Private Data as Byte(). This array is private within a class. The class provides public functions for reading and writing to Data.

This class can be accessed by multiple threads, so I want to avoid a situation where reading from it and writing from it don't happen at the same time.

For now, I am using SyncLock to avoid issues. Can I put SyncLock Data in just the write functions, or does it need to be in the read functions? Or, both?

I don't have a specific code example in mind. I am just curious if there is any benefit to locking for both read and write functions if the writing functions' SyncLock will make writing have exclusive access to it in the first place.

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

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

发布评论

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

评论(2

恬淡成诗 2024-10-17 14:47:55

您应该考虑使用 ReaderWriterLockSlim (或者 ReaderWriterLock 如果您不在 .网4)。

它的目的是允许单个作者,但允许多个读者。对于您所描述的情况,这通常是理想的选择。

否则,您可以使用 SyncLock,但需要锁定读取和写入操作。如果没有两者的锁定,您的读取器可能会在写入器仍在写入时读取数据 - 这将导致您读取半集数据。

Instead of using a SyncLock, you should consider using a ReaderWriterLockSlim (or ReaderWriterLock if you're not in .NET 4).

It is intended to allow a single writer, but multiple readers. This is typically ideal for a situation like the one you're describing.

Otherwise, you can use SyncLock, but you'll need to lock on both read and write operations. Without the lock on both, it's possible for your reader to read data while the writer is still writing - which will cause you to read half-set data.

锦上情书 2024-10-17 14:47:55

您希望锁定读取字节数组的主要原因是为了避免“幻读”或其他不可重复读取 - 如果写入者正在更新数组,则读取者可能会看到一些旧值和一些新值,或者旧值,如果再次读取则使用新值。

例如,如果您有一个包含 [1, 2, 3, 4, 5, 6] 的数组,以及一个采用 SyncLock 并循环遍历该数组并向每个元素添加 1 的写入器线程,则没有 SyncLock 的读者可能会看到像 [2, 3, 4, 4, 5, 6] 这样的奇怪现象——只有真正采用 SyncLock 的线程才会获得任何安全性。

The main reason you would want to lock on reading a byte array is to avoid a "phantom read" or other non-repeatable read -- if a writer is partway through updating the array, a reader may see some old values and some new values, or an old value and then the new value if it reads it again.

For example, if you have an array containing [1, 2, 3, 4, 5, 6], and a writer thread that takes a SyncLock and loops over the array adding 1 to each element, a reader that does not SyncLock may see weirdness like [2, 3, 4, 4, 5, 6] -- only threads that actually take the SyncLock will receive any safety.

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