gpt4 book ai didi

C++:跨线程错误处理问题

转载 作者:太空狗 更新时间:2023-10-29 20:19:32 26 4
gpt4 key购买 nike

通常我使用异常来处理错误,但我遇到的问题是错误适用于与导致错误的线程不同的线程。

基本上窗口有自己的线程,direct3d 设备必须由创建窗口的同一个线程创建和重置。但是创 build 备可能会失败,所以我需要在尝试创建实例的线程中抛出异常,而不是窗口代码

回调函数:

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;

请求窗口线程创 build 备的代码

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;
}

所以基本上我需要由创建 Graphics 对象的异常处理程序捕获 create() 方法抛出的异常,这是另一个线程。

最佳答案

也许您可以使用 Boost.Exception 将调用包装在另一个函数中.

尽管以下代码不起作用,但您可能会明白这一点。

class Context
{
public:
Context(HWND hwnd, const boost::function<void(HWND,LPARAM)>& f, LPARAM lParam)
{
// TODO: reroute call through Wrapper function.
}

void wait()
{
mutex::scoped_lock l(m);
while (!finished)
{
c.wait(l);
}
if (ex)
rethrow_exception(ex);
}

private:
void Wrapper()
{
try
{
f(/*params*/);
}
catch (...)
{
ex = current_exception();
}
mutex::scoped_lock l(m);
finished = true;
c.notify_all();
}

boost::function<void(HWND,LPARAM)> f;
exception_ptr ex;
bool finished;
mutex m;
condition c;
};

void Callback(HWND hwnd, const boost::function<void(HWND,LPARAM)>& f, LPARAM lParam)
{
Context ctx(hwnd, f, lParam);

ctx.wait();
}

关于C++:跨线程错误处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/456873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com