CodeBlanks Logo Icon CodeBlanks

Interlocked

C# kursu · Uzman · Ders 23/47

Interlocked ile atomik işlemleri öğrenirsin.

Interlocked sınıfı

Interlocked sınıfı, lock olmadan atomik işlemler sağlar. Interlocked.Increment(ref n) n'yi bir artırır ve bu işlem atomiktir; başka bir thread aynı anda yaparsa bile sonuç doğru olur.

Benzer şekilde Interlocked.Decrement, Interlocked.Add, Interlocked.Exchange ve Interlocked.CompareExchange mevcuttur. lock'tan çok daha hızlıdır çünkü CPU düzeyinde tek bir komut kullanır.

Interlocked vs lock

Interlocked, basit tek adımlı atomik işlemler için idealdir. Bir sayaç artırmak için lock kullanmak maliyetlidir; Interlocked.Increment aynı işi çok daha ucuza yapar.

Ancak birden fazla işlemi birlikte atomik yapmak istiyorsan hâlâ lock gerekir. Doğru tercih: tek değişken → Interlocked; çok değişken → lock.

Uygulama Interlocked ile sayaç artır

private static int _counter = 0; tanımla. Main'de 3 thread oluştur, her biri Interlocked.Increment(ref _counter); çağırsın (1 kez). Thread'leri Join ile bekle. En son Console.WriteLine($"Sayaç: {_counter}"); yaz. (3 thread * 1 artırma = 3 beklenir.)

Örnek çözümü göster
{_counter}");
Örnek çözüm:
using System;
using System.Threading;

class Program
{
    private static int _counter = 0;

    static void Main()
    {
        Thread t1 = new Thread(() => { Interlocked.Increment(ref _counter); });
        Thread t2 = new Thread(() => { Interlocked.Increment(ref _counter); });
        Thread t3 = new Thread(() => { Interlocked.Increment(ref _counter); });
        t1.Start();
        t2.Start();
        t3.Start();
        t1.Join();
        t2.Join();
        t3.Join();
        Console.WriteLine($"Sayaç: {_counter}");
    }
}

Kendini test et

  1. Interlocked.Increment ne yapar?

    • Lock'la artırma
    • Yeni thread başlatır
    • Atomik artırma
    • GC toplama yapar
    Cevabı göster

    Atomik artırma — Doğru. Interlocked.Increment atomik artırma yapar.

  2. Interlocked metotlarını eşleştir

    Interlocked.Increment
    Atomik +1
    Interlocked.Decrement
    Atomik -1
    Interlocked.Add
    Atomik toplama
    Interlocked.Exchange
    Atomik atama
  3. Interlocked.Increment çağrısı

    Interlocked.____(ref n);
    Cevabı göster
    Interlocked.Increment(ref n);

Uzman bölümündeki tüm dersler