Skip to content

Instantly share code, notes, and snippets.

@airbreather
Last active February 28, 2017 12:46
Show Gist options
  • Save airbreather/45000338536c9967cc89e77b9f70037e to your computer and use it in GitHub Desktop.
Save airbreather/45000338536c9967cc89e77b9f70037e to your computer and use it in GitHub Desktop.
volatile doesn't help you here
using System;
using System.Threading;
namespace ConsoleApp
{
internal static class Program
{
internal static readonly object lockObject = new object();
internal static volatile object obj;
private static void Main(string[] args)
{
while (true)
{
Thread t = new Thread(() =>
{
GetObject();
});
t.IsBackground = true;
t.Start();
Thread.Sleep(400);
}
// sample output:
//// In thread 3, initializing.
//// In thread 6, got object.
//// In thread 7, got object.
//// In thread 3, yielding back.
//// In thread 8, got object.
//// In thread 9, got object.
//// In thread 3, got object.
//// In thread 4, got object.
//// In thread 5, got object.
//// In thread 10, got object.
//// ...
}
private static object GetObject()
{
int threadId = Thread.CurrentThread.ManagedThreadId;
object o = obj;
if (o == null)
{
lock (lockObject)
{
o = obj;
if (o == null)
{
Console.WriteLine("In thread {0}, initializing.", threadId);
Thread.Sleep(1000);
o = obj = new object();
Thread.Sleep(1000);
Console.WriteLine("In thread {0}, yielding back.", threadId);
}
}
}
Console.WriteLine("In thread {0}, got object.", threadId);
return o;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment