在某些場景下,須要週期性的執行耗時操做,好比寫文件。這種場景,有兩個需求點:ios
1.執行一次任務比較耗時,不能影響主業務性能。緩存
2.該任務週期性執行。性能
這種場景:能夠每次在執行任務時啓動一個線程,可是這樣作,當任務執行比較頻繁時,須要屢次建立線程,這樣會有不小的因爲線程屢次建立引發的性能損耗。因此,能夠採用以下方案:測試
啓動一個後臺線程,當有任務時,被喚醒,沒有任務時,線程睡眠。this
#pragma once #include <mutex> #include <condition_variable> #include <string> #include <vector> #include <thread> #include <iostream> using namespace std; class SingleInstance { public: static SingleInstance *getInstance(); static void start(void * arg); void addMsg(string msg); private: SingleInstance(); ~ SingleInstance() = default; private: static SingleInstance * instance; static mutex instanceLock; vector<string> msg; condition_variable msgCV; mutex msgLock; };
實現代碼以下:spa
#include "SingleInstance.h" SingleInstance * SingleInstance::instance = nullptr; mutex SingleInstance::instanceLock; SingleInstance *SingleInstance::getInstance() { if (instance == nullptr) { lock_guard<mutex> lk(instanceLock); if (instance == nullptr) { instance = new SingleInstance(); } } return instance; } SingleInstance::SingleInstance() { thread t(SingleInstance::start,this); t.detach(); // 做爲後臺線程運行 } void SingleInstance::start(void *args) { SingleInstance * instance = static_cast<SingleInstance *>(args); if(instance == nullptr){ return; } while (1) { unique_lock<mutex> lk(instance->msgLock); while (instance->msg.empty()) { instance->msgCV.wait(lk); } cout <<"server receive msg is:"<< instance->msg[0] << endl; instance->msg.clear(); } } void SingleInstance::addMsg(string msg) { lock_guard<mutex> lk(this->msgLock); this->msg.push_back(msg); this->msgCV.notify_one(); }
測試代碼以下:線程
#include <iostream> #include <string> #include <map> #include "LogTime.h" #include "SingleInstance.h" using namespace std; int main(int argc, int * argv[]) { SingleInstance * instance = SingleInstance::getInstance(); instance->addMsg("hello"); for (int i = 0; i < 1e5; i++); instance->addMsg("world"); system("pause"); }
測試結果以下:3d
尤爲是對於有特殊需求的日誌這種場景,能夠採用這種方式。固然,在單條日誌數據量不太的場景下,能夠先將日誌寫在緩存裏,當緩存滿了以後,再將日誌發送給sever進行寫文件日誌