一个简单的多线程下的singleton实现

首先看一个简单的单线程的单例模式

(1)构造函数私有化

(2)提供一个全局的静态方法(静态访问点)

(3)在类中定义一个静态指针,指向本类的变量 的静态变量指针

#include<iostream>
using namespace std;

class singelton
{
public:
	static singelton* getinstance()
	{
		if (m_psl == NULL)
		{
			m_psl = new singelton;
		}
		return m_psl;
	}


	static void free_instance()
	{
		if (m_psl != NULL)
		{
			delete m_psl;
		}
		m_psl = NULL;
	}
private:
	singelton()
	{
		cout << "singelton contructor" << endl;
	}
private:
	static singelton  *m_psl;
};


int main()
{
	singelton* ps1 = singelton::getinstance();
	singelton* ps2 = singelton::getinstance();
	if (ps1 == ps2)
	{
		cout << "the same" << endl;
	}
	else
	{
		cout << "diffence" << endl;
	}

	system("pause");
	return 0;
}

都知道多线程下,全局的变量访问顺序都是随机的,对于 单例变量也是如此,不加锁就会在每个线程中都创建一个实例,此时就不是单例了

如下是一个简单的多线程下的单例实现(win)


#include"windows.h"
#include"winbase.h"
#include<process.h>


using namespace std;


CRITICAL_SECTION  cs;  //定义一个临界区变量 ,用来对singleton的初始化函数加锁


class singleton
{
private:
	singleton() //多线程下不是线程安全函数
	{
		cout << "构造函数" << endl;
		//Sleep(1000);
	}
	~singleton();
public:
	static singleton* get_singleton()
	{
		EnterCriticalSection(&cs);  // 开始加锁,在没有解锁前只有一个线程可以访问
		if (single == NULL)
		{
			count++;
			single = new singleton();
		}
		LeaveCriticalSection(&cs);  //解锁 
		//另一种double check的方法
		/*-----------------------------------
		if (single == NULL)
		{
			EnterCriticalSection(&cs);  
			if (single == NULL)
			{
				count++;
				single = new singleton();
			}
			LeaveCriticalSection(&cs);  
		}
		-----------------------------------*/
		return single;
	}
	static singleton *release_singleton()
	{
		if (single != NULL)
		{
			delete single;
			single = NULL;
		}
	}
	static void print()
	{
		cout << "singleton print test" << endl;
	}


private:
	static singleton* single;
	static int count;


};
singleton* singleton::single = NULL;
int singleton::count = 0;


void main01()
{
	singleton* ps1 = singleton::get_singleton();
	singleton* ps2 = singleton::get_singleton();
	if (ps1 == ps2)
	{
		cout << "the same" << endl;
	}
	else
	{
		cout << "diffence" << endl;
	}


}
void  myfunc(void *)
{
	//cout << "线程函数开始" << endl;  不会清空缓冲区
	cout << "线程函数开始\n";
	singleton::get_singleton()->print();


}


int _tmain(int argc, _TCHAR* argv[])
{
	//main01();
	//_CRTIMP uintptr_t __cdecl _beginthread (_In_ void (__cdecl * _StartAddress) (void *),
	//_In_ unsigned _StackSize, _In_opt_ void * _ArgList);
	InitializeCriticalSection(&cs);
	
	HANDLE hThread[10];
	for (int i = 0; i < 3; i++)
	{
		hThread[i] = (HANDLE)_beginthread(myfunc, 0, NULL);
	}


	int i = 0;
	for (; i < 3; i++)
	{
		//等待 所有子线程均运行完毕后执行下面的代码
		//INFINITE 表示 死等 
		WaitForSingleObject(hThread[i],INFINITE);
	}
	system("pause");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章