336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


For the example in the preceding section, we assumed that multiple threads can throw exceptions and therefore need a container to hold them all. If there is a single exception from a single thread at a time, then you do not need a shared container and a mutex to synchronize access to it. You can use a single global object of the type std::exception_ptr to hold the exception transported between threads.

The std::current_exception() is a function that is typically used in a catch clause to capture the current exception and create an instance of std::exception_ptr. This is done to hold a copy or reference (depending on the implementation) to the original exception, which remains valid as long as there is an std::exception_ptr pointer available that refers to it. If this function is called when no exception is being handled, then it creates an empty std::exception_ptr.

The std::exception_ptr pointer is a wrapper for an exception captured with std::current_exception(). If default constructed, it does not hold any exception. Two objects of this type are equal if they are both empty or point to the same exception object. The std::exception_ptr objects can be passed to other threads where they can be rethrown and caught in a try...catch block.

The std::rethrow_exception() is a function that takes std::exception_ptr as an argument and throws the exception object referred to by its argument.

쓰레드에서 exception 발생치 처리하기 위한 코드로 2개 이상의 thread에서 exception이 발생시 vector에 exception 객체를 담아서 관리할 필요가 있다.

catch 구문에서 lock_guard를 통해서 두개의 thread에서 동시에 exception 처리를 위한 mutex 설정이 필요하며 단일 thread의 경우에는 굳이 mutex 및 전역 변수에 vector로 exception 객체를 관리할 필요가 없다.


#include 
#include 
#include 
#include 
#include 

std::vector g_exceptions;
std::mutex g_mutex;

void func1()
{
	throw std::exception("exception 1");
}

void func2()
{
	throw std::exception("exception 2");
}

void thread_func1()
{
	try
	{
		func1();
	}
	catch (...)
	{
		std::lock_guard lock(g_mutex);
		g_exceptions.push_back(std::current_exception());
	}
}

void thread_func2()
{
	try
	{
		func2();
	}
	catch (...)
	{
		std::lock_guard lock(g_mutex);
		g_exceptions.push_back(std::current_exception());
	}
}

int main() {
	g_exceptions.clear();

	std::thread t1(thread_func1);
	std::thread t2(thread_func2);
	t1.join();
	t2.join();

	for (auto const & e : g_exceptions)
	{
		try
		{
			if (e != nullptr)
				std::rethrow_exception(e);
		}
		catch (std::exception const & ex)
		{
			std::cout << ex.what() << std::endl;
		}
	}

	return 0;
}


'ⓟrogramming > C++' 카테고리의 다른 글

[Thread] Synchronizing access to shared data with mutexes and locks  (0) 2018.01.04
[Thread] Working with threads  (0) 2018.01.04
Visual Studio 에서 Boost 사용법  (0) 2016.07.28
임시객체  (1) 2016.05.11
rvalue  (0) 2016.05.11
블로그 이미지

뚱땡이 우주인

,