Tag Archives: singleton

Thread is waiting for init_thread_header and init_thread_wait

The other day I ran into an issue where a thread got stuck on accessing a singleton. It was quite curious because there was no locking with mutexes or critical sections going on, yet the thread stalled. The callstack showed init_thread_header and init_thread_wait as the top most functions of the callstack, so the thread was definitely waiting for something… As it turns out, the constructor of the singleton class was calling some functions, which in turn would try to access the singleton again, this would of course result in an endless loop, depending on which implementation of singletons you use.
If you would instantiate the singleton with new, there would be an endless loop, and the stack would overflow. But if you used a static instance, the thread would simply stall at completion of the first loop, and Visual Studio would not complain, warn, or break.

Here is a simple example of how you can recreate this issue.

class MySingleton
{
public:
	static MySingleton& GetInstance()
	{
		static MySingleton instance;
		return instance;
	}

	MySingleton()
	{
		MySingleton::GetInstance(); // This is obviously bad
	}

	~MySingleton()
	{
	}
};

int main(void)
{
	MySingleton::GetInstance();
}

Of course the code I was working with was not so straightforward. So you would definitely have to look at the entire callstack to find the source of the problem.

Interesting issue, something to look out of in case your code stalls while accessing a singleton. But then again, we probably shouldn’t be calling any functions in constructors anyway… 🙂