C++ 11 多线程退出以及创建

例码:

 
 
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <functional>
#include <atomic>
 
class Test {
public:
	Test() {
		cnt_.store(0);
		exit_.store(false);
		for (int i = 0; i < 5; ++i)
			std::thread(std::bind(&Test::Fn1, this)).detach();
	};
	void Fn1() {
		cnt_++;
		while (1)
		{
			if (exit_)
				break;
			std::this_thread::sleep_for(std::chrono::milliseconds(300));
		}
		std::cout << "thread:" << std::this_thread::get_id << ",exit!" << std::endl;
		cnt_--;
	}
	~Test() {
		std::this_thread::sleep_for(std::chrono::seconds(4));
		exit_.store(true);
		while (cnt_);
 
	};
private:
	std::condition_variable  cv_;
	std::mutex               mtx_;
	std::atomic<int>         cnt_;
	std::atomic<bool>        exit_;
};
int main() {
 
	Test* t = new Test();
	delete t;
	getchar();
	return 0;
}
 

猜你喜欢

转载自blog.csdn.net/cyy1104/article/details/129799544