保证在函数在多线程环境中只被调用一次 std::once_flag m_flag; }; int main() { ThreadPool pool; //pool.Start(2); std::thread thd1([&pool] { for (int i = 0; i < 10; i++) { auto thdId = this_thread::get_id(); pool.AddTask([thdId] { cout << "1.thread id: " << thdId << endl; }); } }); std::thread thd2([&pool] { for (int i = 0; i < 10; i++) { auto thdId = this_thread::get_id(); pool.AddTask([thdId] { cout << "2.thread id: " << thdId << endl; }); } }); this_thread::sleep_for(std::chrono::seconds(2)); getchar(); pool.Stop(); thd1.join(); thd2.join(); }
对象池
对象池对于创建开销较大的对象来说很有意义,为了避免重复创建开销较大的对象,可以通过对象池来优化.
对象池的思路比较简单,实现创建好一批对象,放到一个集合中,每当程序需要新的对象时,就从对象池中获取,程序用完该对象后都会把该对象归还给对象池.这样会避免重复创建对象,提高程序性能.
#include
#include
#include
#include