var task1 = Task.Factory.StartNew(() => { for (int i = 0; i < 50000; i++) Interlocked.Increment(ref _variable); }); var task2 = Task.Factory.StartNew(() => { for (int i = 0; i < 100000; i++) Interlocked.Decrement(ref _variable); }); var task3 = Task.Factory.StartNew(() => { for (int i = 0; i < 25001; i++) Interlocked.Add(ref _variable, 2); }); Task.WaitAll(task1, task2, task3); Console.WriteLine(_variable); //2
, a także operacje podstawienia lub warunkowego podstawienia (jeżeli zmienna ma wartość x, to podstaw y).
private static void Exchange() { Thread thread1 = new Thread(new ThreadStart(A)); thread1.Start(); thread1.Join(); // Written [2] Console.WriteLine(Interlocked.Read(ref _value)); } private static void A() { // Replace value with 10. Interlocked.Exchange(ref _value, 10); // CompareExchange: if 10, change to 20. long result = Interlocked.CompareExchange(ref _value, 20, 10); // Returns original value from CompareExchange [1] Console.WriteLine(result); }
Mając do dyspozycji te metody, możemy budować bardziej skomplikowane równoległe algorytmy.
Brak komentarzy:
Prześlij komentarz