文章目錄
- call_once
- 示例一
- 示例二
call_once
std::call_once
是 C++11 標準庫中的一個函數,用于確保某個函數只會被調用一次。
單例設計模式是一種常見的設計模式,用于確保某個類只能創建一個實例。由于單例實例是全局唯一的,因此在多線程環境中使用單例模式時,需要考慮線程安全的問題。
下面是一個簡單的單例模式的實現:
示例一
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
using namespace std;
static once_flag m_onceFlag;
class Log {
public:static Log* getInstance(){call_once(m_onceFlag, init);//保證有一個對象cout << &m_instance << endl;return m_instance;}static void init(){if (m_instance == nullptr){m_instance = new Log;}}void printStr(string str){cout <<__TIME__ <<"::"<<str << endl;}static Log* m_instance;
};
Log* Log::m_instance = nullptr;
void print_thread(string str)
{Log::getInstance()->printStr(str);
}
int main()
{thread t1(print_thread,"t1");thread t2(print_thread, "t2");t1.join();t2.join();while (1){}return 0;
}
示例二
#include <iostream>
using namespace std;
#include <thread>
#include <mutex>once_flag g_flag;void do_once(int a, string b) {cout << "name: " << b << ", age: " << a << endl;
}void do_something(int age, string name) {static int num = 1;call_once(g_flag, do_once, 19, "luffy");cout << "do_something() function num = " << num++ << endl;
}int main() {thread t1(do_something, 20, "ace");thread t2(do_something, 20, "sabo");thread t3(do_something, 20, "luffy");t1.join();t2.join();t3.join();return 0;
}
執行結果
name: luffy, age: 19
do_something() function num = 1
do_something() function num = 2
do_something() function num = 3
通過輸出的結果可以看到,雖然運行的三個線程中都執行了任務函數do_something()但是call_once()中指定的回調函數只被執行了一次,我們的目的也達到了。