Question of the day: Threading
Here’s a little question about Threading – this would be a great interview question, in my opinion!
Given the code below:
public class Producer
{
[ThreadStatic]
readonly static private Producer _instance = new Producer();
static private int _instanceCount;
readonly private int _instanceId;
private Producer()
{
_instanceId = ++_instanceCount;
}
static public Producer Instance
{
get { return _instance; }
}
public string Name
{
get
{
return String.Format("Instance {0} of {1}",
_instanceId, _instanceCount);
}
}
}
public class Consumer
{
public Consumer()
{
Thread t1 = new Thread(IdentifyProducer);
t1.Start();
Thread t2 = new Thread(IdentifyProducer);
t2.Start();
t1.Join();
t2.Join();
}
public void IdentifyProducer()
{
Console.WriteLine(Producer.Instance.Name);
}
}
What will happen when you create a new instance of the Consumer class?

Stu just pointed out that this question was never answered!
At an initial glance, it looks like the code is a trick question – the ThreadStatic attribute applies to _instance only, and not to _instanceId – so the code should execute normally and produce:
Instance 1 of 2
Instance 2 of 2
But if you run the code, you’ll get a null reference exception!
The problem lies in the initialisation of the ThreadStatic member – it only runs once, on the first thread that runs the initialisation code. So, poor old Thread 2 always has a null _instance!
The only way around the problem is to make the field non-readonly, and then modify the Instance property accessor to do the initialisation there:
[ThreadStatic]
static private Producer _instance;
static public Producer Instance
{
get { return _instance ?? (_instance = new Producer()); }
}
Hope that makes sense!
Nice one Gerrod!