【发布时间】:2010-10-02 04:41:00
【问题描述】:
一般来说,我使用异常来处理错误,但是我遇到的问题是错误适用于与导致它的线程不同的线程。
基本上,窗口有自己的线程,direct3d 设备必须由创建窗口的同一线程创建和重置。但是创建设备可能会失败,所以我需要在试图创建实例的线程中抛出异常,而不是窗口代码
回调函数:
void Callback(HWND hwnd, boost::function<void(HWND,LPARAM)> call, LPARAM lParam)
{
//Make our stack allocated function object into a heap allocated one
boost::function<void(HWND,LPARAM)> *callH = new boost::function<void(HWND,LPARAM)>(call);
//send a message with a pointer to our function object in the WPARAM
PostMessage(hwnd, WM_CALLBACK, (unsigned)callH, lParam);
}
LRESULT CALLBACK HookProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
//check for our custom message
if(msg == WM_CALLBACK)
{
//retreive the function pointer from the WPARAM
boost::function<void(HWND,LPARAM)> *callH = (boost::function<void(HWND,LPARAM)>*)wParam;
//call it
(*callH)(hwnd,lParam);
//delete our heap allocated function object
delete callH;
return 0;
}
else
//if there was nothing relevant to us, call the old message procedure
return CallWindowProc(hooked[hwnd], hwnd, msg, wParam, lParam);
}
//std::map<HWND, WNDPROC> hooked;
请求窗口线程创建设备的代码
Graphics::Graphics(IWindow *_window, Size2<unsigned> _size)
:lost(false), reset(false), refCnt(0), backCol(0xFF000000),
started(false), exited(false),
window(_window), size(_size)
{
window->AddRef();
HWND hwnd = *((HWND*)window->GetHandle());
CallbackHook(hwnd);
Callback(hwnd, boost::bind(&Graphics::create, this), 0);
while(!started)Sleep(100);
}
void Graphics::create()
{
...code that may throw various exceptions
started = true;
}
所以基本上我需要 create() 方法抛出的异常被创建 Graphics 对象的异常处理程序捕获,这是另一个线程。
【问题讨论】:
标签: c++ multithreading exception error-handling