I have a member variable defined as:
HWND WindowHandle.
I'm trying to capture the variable and assign to it in the Lambda. So the compiler gave me a warning and suggested that I capture "this". I did, but now the Handle is only valid within the Lambda :S Inother words, it is NULL outside of the Lambda.
class Foo
{
private:
HWND WindowHandle;
public:
Foo();
void MakeWindow(.......);
HWND GetWindowHandle() {return WindowHandle;};
};
Foo::Foo(){}
Foo::MakeWindow(.......)
{
Thread = std::thread([ClassName, Title, Width, Height, this]{
WindowHandle = CreateWindowEx(0, ClassName.c_str(), Title.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, Width, Height, 0, 0, GetModuleHandle(NULL), 0);
if(WindowHandle)
{
ShowWindow(WindowHandle, SW_SHOWDEFAULT);
MSG msg;
while(GetMessage(&msg, 0, 0, 0))
DispatchMessage(&msg);
}
});
}
int main()
{
Foo F;
F.MakeWindow(........);
std::cout<<std::boolalpha<<(F.GetWindowHandle() == NULL); //writes true.
}
The above creates the window perfectly fine! It's just the Handle is null. How can I get the Handle from within the Lambda to my class Member?
That's because your code has a race condition. By the time you check the value in main(), the thread has not run yet, so WindowHandle is still NULL.
Unless you didn't actually start the thread yet. In that case, since the thread hasn't executed, WindowHandle is still NULL.
In any event, you need to synchronize access to WindowHandle between threads with a mutex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With