gpt4 book ai didi

C# 复杂线程同步

转载 作者:行者123 更新时间:2023-11-30 19:41:06 24 4
gpt4 key购买 nike

我有相当复杂的线程同步案例。我有一个从不同线程访问的集合。一个线程,我们将其命名为“控制线程”,更新一个集合。其他线程读取集合('Reading threads')。我要实现的逻辑如下:

  1. 读取线程可以同时读取集合。
  2. 当控制线程需要更新集合时:
    • 在当前正在处理集合的所有读取线程完成其工作之前,控制线程不应开始更新。
    • 但是当控制线程正在等待完成读取线程时,其他尚未开始处理集合的读取线程不应启动 - 它们应该等到控制线程更新集合。

我应该使用什么线程同步技术?

最佳答案

使用 ReaderWriterLockSlim类:

Represents a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing.

Use ReaderWriterLockSlim to protect a resource that is read by multiple threads and written to by one thread at a time. ReaderWriterLockSlim allows multiple threads to be in read mode, allows one thread to be in write mode with exclusive ownership of the lock, and allows one thread that has read access to be in upgradeable read mode, from which the thread can upgrade to write mode without having to relinquish its read access to the resource.

乔·阿尔巴哈里的 Threading in C#是一个很好的资源。

关于C# 复杂线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21073918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com