Skip to content

Instantly share code, notes, and snippets.

@rodion-m
Created January 19, 2023 18:31
Show Gist options
  • Save rodion-m/b919c7e645edeba730faa3ee96eb7580 to your computer and use it in GitHub Desktop.
Save rodion-m/b919c7e645edeba730faa3ee96eb7580 to your computer and use it in GitHub Desktop.
SetColor with CAS
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);
}
}
@rodion-m
Copy link
Author

Output:

255, 255, 255
0, 0, 0
0, 255, 255
255, 0, 0
255, 255, 0
0, 0, 255
255, 0, 255
0, 255, 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment