c++11实现子线程如果超时,则主线程提前退出

代码

#include
#include
#include
#include
#include
#include

using namespace std;

class A {
public:
	void play(int d[4], int& ans, std::promise<void>& prom)
	{
		Sleep(5000);
		for (int i = 0; i < 4; ++i) d[i] = i + 2;
		ans = 666;
		

		prom.set_value();
	}
};



int main()
{
	A* a = new A;
	int d[4]{ 0 };
	int ans = 0;

	std::promise<void> prom;
	std::future<void> fut = prom.get_future();

	std::thread taskThread(&A::play, a, std::ref(d), std::ref(ans), std::ref(prom));
	
	auto timeout = std::chrono::seconds(1);
	if (fut.wait_for(timeout) == std::future_status::timeout)
	{
		taskThread.detach();
		for (int i = 0; i < 4; ++i) cout << d[i] << " ";
		cout << endl;
		return -255;
	}
	else{
			taskThread.join();
		}
	
	for (int i = 0; i < 4; ++i) cout << d[i] << " ";
	cout << endl;


	return 0;
}

你可能感兴趣的:(c++学习,c++,算法,开发语言)