Library initialization -- pthread_once in Win32 implementation

Hello. I am trying to make a fully thread-safe initialization function for my library and I couldn't easily find an alternative to pthread_once, which should solve the problem very easily. I've come to this code:


void libInit (void)
{
#ifdef WIN32
	static volatile int initialized = 0;
	static HANDLE mtx;

	if (!initialized)
	{
		if (!mtx)
		{
			HANDLE mymtx;
			mymtx = CreateMutex(NULL, 0, NULL);
			if (InterlockedCompareExchangePointer(&mtx, mymtx, NULL) != NULL)
				CloseHandle(mymtx);
		}

		WaitForSingleObject(mtx);
		if (!initialized)
		{
			libInitInternal();
			initialized = 1;
		}
		ReleaseMutex(mtx);
	}
#else
	static pthread_once_t initialized = PTHREAD_ONCE_INIT;

	pthread_once(&initialized, libInitInternal);
#endif
}

The libInitInternal() call leads to a thread-unsafe function, that initializes the library.

I would like to hear any suggestions on what I could be doing wrong or whether you know about a better solution.

以上就是Library initialization -- pthread_once in Win32 implementation的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏