c++ 學習之 多線程(七)call_once

c++ 學習之 多線程(七)call_once

前言

有時候我們需要在第一次執行某個函數時進行一個特定的操作,後面再次執行該函數時,就不再進行這個特定操作了,std::call_once 很好的解決了這個問題。

正文

1.call_once 的使用

call_once 需要和 std::once_flag 這個標記結合使用。所以往往將std::once_flag 設置位全局變量。

#include<thread>
#include<mutex>
#include<stdio.h>
using namespace std;
mutex m;
once_flag flag;
void Print()
{
   printf("666\n");
}
void test()
{
  call_once(flag,Print);
}
int main()
{
     thread t1(test);
     thread t2(test);
     t1.join();
     t2.join(); 
}

輸出結果: 666
看一看到,結合call_once只執行了 一次Print()。

2.使用call_once 實現單例模式

之前的文章中提到過單例模式,單例模式的初始化問題完全可以使用call_once 來解決。尤其是再多線程中,使用call_once 的效率比雙重檢測要高一些。

#include<stdio.h>
#include<mutex>
using namespace std;
mutex m;
once_flag flag;
class Singleton
{
private :
 Singleton() {};
 Singleton(const Singleton&) {};
 static Singleton* m_instance;
 static void CreatInstance()
 {
  if (Singleton::m_instance == nullptr)
  {
   Singleton::m_instance = new Singleton;
   static Recover recover;
  }
 }

 class Recover
 {
 public:
  ~Recover()
  {
   if (Singleton::m_instance != nullptr)
   {
    delete Singleton::m_instance;
    Singleton::m_instance = nullptr;
   }
  }
 };
public:
 static Singleton& GetInstance()
 {
    call_once(flag, CreatInstance);
    return *Singleton::m_instance;
 }
 
};
Singleton* Singleton::m_instance = nullptr;
int main()
{
 Singleton::GetInstance();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章