Created
January 19, 2023 18:31
-
-
Save rodion-m/b919c7e645edeba730faa3ee96eb7580 to your computer and use it in GitHub Desktop.
SetColor with CAS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var saved = new HashSet<string>(); | |
while (saved.Count < 8) | |
{ | |
RGB color = new RGB(0, 0, 0); | |
//Поток 1: | |
var task1 = Task.Run(() => | |
{ | |
color.SetColor(255, 255, 255); | |
}); | |
//Поток 2: | |
var task2 = Task.Run(() => | |
{ | |
var line = $"{color.R}, {color.G}, {color.B}"; | |
if (!saved.Contains(line)) | |
{ | |
saved.Add(line); | |
Console.WriteLine(line); | |
} | |
}); | |
Task.WaitAll(task1, task2); | |
} | |
struct RGB | |
{ | |
public long R, G, B; | |
public RGB(long r, long g, long b) | |
{ | |
(R, G, B) = (r, g, b); | |
} | |
public void SetColor(long r, long g, long b) | |
{ | |
Interlocked.CompareExchange(ref R, r, 0); | |
Interlocked.CompareExchange(ref G, g, 0); | |
Interlocked.CompareExchange(ref B, b, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: