首頁 > 後端開發 > C++ > 如何使用SemaphoreSlim正確實現非同步鎖定,防止間歇性檔案存取錯誤?

如何使用SemaphoreSlim正確實現非同步鎖定,防止間歇性檔案存取錯誤?

Barbara Streisand
發布: 2025-01-15 09:49:50
原創
961 人瀏覽過

How to Correctly Implement Asynchronous Locking Using SemaphoreSlim to Prevent Intermittent File Access Errors?

透過非同步鎖定解決間歇性檔案存取錯誤

ImageProcessor 庫最近在快取更新期間遇到間歇性檔案存取錯誤,這是由於有缺陷的非同步鎖定造成的。本文分析了最初的錯誤實現並提供了一個可靠的解決方案。

原始方法使用雜湊 URL 作為非同步鎖定的金鑰,將 SemaphoreSlim 實例儲存在 ConcurrentDictionary 中以確保單鍵鎖定。 關鍵缺陷在於在SemaphoreSlim釋放信號量之前從字典中同步刪除。這種競爭條件導致文件存取衝突。

以下程式碼片段說明了有問題的鍵/SemaphoreSlim引用:

private static readonly Dictionary<object, RefCounted<SemaphoreSlim>> SemaphoreSlims
                        = new Dictionary<object, RefCounted<SemaphoreSlim>>();

private SemaphoreSlim GetOrCreate(object key)
{
    RefCounted<SemaphoreSlim> item;
    lock (SemaphoreSlims)
    {
        if (SemaphoreSlims.TryGetValue(key, out item))
        {
            ++item.RefCount;
        }
        else
        {
            item = new RefCounted<SemaphoreSlim>(new SemaphoreSlim(1, 1));
            SemaphoreSlims[key] = item;
        }
    }
    return item.Value;
}
登入後複製

下面是更正後的AsyncDuplicateLock類,解決了並發問題:

public sealed class AsyncDuplicateLock
{
    private sealed class RefCounted<T>
    {
        public RefCounted(T value)
        {
            RefCount = 1;
            Value = value;
        }

        public int RefCount { get; set; }
        public T Value { get; private set; }
    }

    private static readonly Dictionary<object, RefCounted<SemaphoreSlim>> SemaphoreSlims
                        = new Dictionary<object, RefCounted<SemaphoreSlim>>();

    private SemaphoreSlim GetOrCreate(object key)
    {
        RefCounted<SemaphoreSlim> item;
        lock (SemaphoreSlims)
        {
            if (SemaphoreSlims.TryGetValue(key, out item))
            {
                ++item.RefCount;
            }
            else
            {
                item = new RefCounted<SemaphoreSlim>(new SemaphoreSlim(1, 1));
                SemaphoreSlims[key] = item;
            }
        }
        return item.Value;
    }

    public IDisposable Lock(object key)
    {
        GetOrCreate(key).Wait();
        return new Releaser { Key = key };
    }

    public async Task<IDisposable> LockAsync(object key)
    {
        await GetOrCreate(key).WaitAsync().ConfigureAwait(false);
        return new Releaser { Key = key };
    }

    private sealed class Releaser : IDisposable
    {
        public object Key { get; set; }

        public void Dispose()
        {
            RefCounted<SemaphoreSlim> item;
            lock (SemaphoreSlims)
            {
                item = SemaphoreSlims[Key];
                --item.RefCount;
                if (item.RefCount == 0)
                    SemaphoreSlims.Remove(Key);
            }
            item.Value.Release();
        }
    }
}
登入後複製

此修訂後的實現確保信號量從字典中刪除之前被釋放,消除了競爭條件並解決了間歇性文件存取錯誤。

以上是如何使用SemaphoreSlim正確實現非同步鎖定,防止間歇性檔案存取錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板