I need to run for example:
ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE);
as new thread, but I don't know how. I tried this:
HANDLE hThread = (HANDLE) _beginthread(ShellExecute(NULL, "open", "program.exe", NULL, NULL, SW_HIDE), 0, NULL);
WaitForSingleObject( hThread, INFINITE );
but obviously it's wrong and can't be compiled. How should I do this?
What you tried is indeed obviously wrong, but the question is whether you understand what's wrong with it.
_beginthread
takes a pointer to function (with a specific prototype and calling convention) as its first parameter.When you write
you're trying to pass
_beginthread
the result of callingShellExecute
(in the current thread) which is anHINSTANCE
, while_beginthread
expects avoid( __cdecl *)( void * )
(pointer to a__cdecl
function taking onevoid*
parameter and returningvoid
).Not only your code doesn't work because you're trying to pass an
HINSTANCE
where a function to pointer is expected, it doesn't make any sense. Have you read the_beginthread
documentation? There are examples there. Plural.What you meant to write is:
given:
Or, in a more compact and easy to read form:
Unless you're doing something beyong what we're seeing here, David'scomment is probably right and you should be using
std::thread
orstd::async
.Also note that taking the result of
_beginthread
(int contrast to the result of_beginthreadex
orCreateThread
) in unsafe because it may not be valid, as noted in the documentation. Not only that, but_beginthread
's return value isn't really aHANDLE
(it is some sore of a handle, but not aHANDLE
!), so you can'tWaitForSingleObject
on it:Since this thread only calls one function and exits, it almost maximizes the chance of this handle not being valid. And even if it were, you still couldn't use it to
WaitForSingleObject
.