日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

c++11 call_once 使用方法

發布時間:2023/12/15 c/c++ 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c++11 call_once 使用方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

call_once是c++11中引入的新特性,用于保證某個函數只調用一次,即使是多線程環境下,它也可以可靠地完成一次函數調用。特別適用于某個初始化只執行一次的場景。

若調用call_once一切順利,將會翻轉once_flag變量的內部狀態,再次調用該函數時,所對應的目標函數不會被執行。
若調用call_once中發生異常,不會翻轉once_flag變量的內部狀態,再次調用該函數時,目標函數仍然嘗試執行。
下面代碼是在win7+vs2015編譯器測試通過,演示了如何使用c++11 中的call_once方法
?

#include "stdafx.h" #include <iostream> #include <chrono> #include <thread> #include <mutex>//單利模式應用 class CSinglton { private://(1)私有額構造函數CSinglton() {}//在析構函數中釋放實例對象~CSinglton(){if (pInstance != NULL){delete pInstance;pInstance = NULL;}} public://(3)獲得本類實例的唯一全局訪問點static CSinglton* GetInstance(){//若實例不存在,則嘗試創建實例對象if (NULL == pInstance){//call_once object makes sure calling CreateInstance function only one time;//it will be safe without lock;try {std::call_once(m_flag, CreateInstance);}catch (...) {std::cout << "CreateInstance error\n";}}//實例已經存在,直接該實例對象return pInstance;}static void CreateInstance(){pInstance = new(std::nothrow) CSinglton();//分配失敗,是返回NULL;if (NULL == pInstance){throw std::exception();}}private:static CSinglton* pInstance;//(2)唯一實例對象static std::once_flag m_flag; };CSinglton* CSinglton::pInstance = NULL; //構造 once_flag 對象,內部狀態被設為指示函數仍未被調用。 std::once_flag CSinglton::m_flag;//輔助測試代碼 std::mutex g_mutex; void PrintInstanceAddr() {std::this_thread::sleep_for(std::chrono::microseconds(1));//get instance CSinglton* pIns = CSinglton::GetInstance();//print instance addrstd::lock_guard<std::mutex> lock(g_mutex);std::cout << pIns << std::endl; }int main() {std::thread td[5];//multhread get instance addr;for (int i = 0; i < 5; i++){td[i] = std::thread(PrintInstanceAddr);}for (int i = 0; i < 5; i++){td[i].join();}return 0; }

運行結果:

0076E778 0076E778 0076E778 0076E778 0076E778

注意:上面的單例模式即直接按下面那樣不加鎖,不用std::call_once調用,在多線程中會因為線程競爭而導致不正確的結果出現。

//(3)獲得本類實例的唯一全局訪問點static CSinglton* GetInstance(){//若實例不存在,則嘗試創建實例對象if (NULL == pInstance){try {CreateInstance);}catch (...) {std::cout << "CreateInstance error\n";}}//實例已經存在,直接該實例對象return pInstance;}

本文轉自:https://blog.csdn.net/c_base_jin/article/details/79307262?

參考資料:
http://zh.cppreference.com/w/cpp/thread/call_once
http://www.cplusplus.com/reference/mutex/call_once/?kw=call_once

總結

以上是生活随笔為你收集整理的c++11 call_once 使用方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。