Let’s say I have the following code:
typedef std::function<void ()> func_type;
void some_func()
{
// Irrelevant stuff here. Might take some time...
}
DWORD WINAPI thread_proc(LPVOID lpParameter)
{
func_type& func = *static_cast<func_type*>(lpParameter);
func();
return 0;
}
int main()
{
HANDLE handle;
{
std::function<void ()> my_func(some_func);
handle = ::CreateThread(NULL, 0, &thread_proc, &my_func, 0, NULL);
// Here we consider my_func won't be destroyed before its operator() is called in the other thread.
// I know nothing guarantees that, but let's just say it does for this sample.
}
::WaitForSingleObject(handle, INFINITE);
return EXIT_SUCCESS;
}
My current implementation seems to work, but this doesn’t prove that I’m not facing undefined behavior.
Here my_func might be destroyed before the call to its operator() returns. But since I’m not refering to my_func anywhere in some_func(), is it really a problem ?
Note: I cannot use std::thread or boost::thread unfortunately. I wish I could.
If it gets destroyed before
func()happens, then you’re calling a member function on an invalid object. You need to make a copy that will live at least untilfunc()call.