std call_once使用

##callonce使用

#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <atomic>
#include <mutex>
/**
 *多线程达到同步效果
 1原子操作顺序
 2互斥量+锁
 3条件变量
 *Date :[10/8/2018 ]
 *Author :[RS]
 */
class Data {
public:
	void operator()() {
		std::call_once(mOnceFlag, &Data::init, this);
		std::cout << "work"<<std::endl;
	}
protected:
	void init() {
		std::cout << "init" << std::endl;
		mMecory = new char[24];
	}
	mutable std::once_flag mOnceFlag;
	mutable char* mMecory;
};

int main() {
	std::cout.sync_with_stdio(true);
	Data d;
	std::thread t1(std::ref(d));
	std::thread t2(std::ref(d));
	std::thread t3(std::ref(d));
	t1.join();
	t2.join();
	t3.join();

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/river472242652/article/details/82964762