C++11單例設計模式(雙檢查鎖)

  • 2020 年 2 月 15 日
  • 筆記

       單例設計模式就是一個類只能實例化出一個對象,不能實例化出多個對象,單例模式分為兩種,一種是餓漢單例模式,是指在類創建的時候就已經實例化出了一個對象,好處是這個模式沒有線程安全問題,壞處是浪費資源,不管之後有沒有用到,都會先實例化一個對象,代碼如下:

std::mutex mlock;    class Solution {  private:  	Solution() {}  	static Solution* ptr;  public:  	static Solution* Create() {  		return ptr;  	}  };    Solution* Solution::ptr = new Solution();

       還有一種是懶漢模式,顧名思義,當你需要用它的時候才去實例化對象,如果多個線程同時去實例化對象,那麼產生的對象可能不唯一,所以存在線程安全的問題,避免這個線程安全的解決辦法是用雙檢查鎖(double checked locking),不是很難理解,具體實現過程就不在講解,直接看代碼吧:

#include <iostream>  #include <mutex>    std::mutex mlock;    class Solution {  public:  	static Solution* Create() {  		if (ptr == NULL) {  			std::unique_lock<std::mutex> MyUniqueLock(mlock);  			if (ptr == NULL) {  				ptr = new Solution();  				static Destructor s;  			}  		}  		return ptr;  	}  	class Destructor {  	public:  		~Destructor() {  			if (Solution::ptr != NULL) {  				delete Solution::ptr;  				Solution::ptr = NULL;  			}  		}  	};  private:  	static Solution* ptr;  	Solution() {};  };    Solution *(Solution::ptr) = NULL;    void Thread() {  	Solution* tmp = Solution::Create();  	std::cout << "My Thread Function" << std::endl;  }    int main()  {  	std::thread t1(Thread);  	std::thread t2(Thread);  	t1.join();  	t2.join();  	return 0;  }