Reputation: 53
I started studying multithreading. And I've found 2 ways to use it ic C++. First is by thread
#include <thread>
...
std::thread t(function);
<< some code>>
t.join(); //(or detach)
And second is by process
#include <process.h>
...
_beginthreadex('bunch of parameters');
<< some code >>
_endthreadex()
So what, if anything, is the difference? And if there is a difference, when should one be used instead of the other?
Upvotes: 3
Views: 1516
Reputation: 117258
You missed one: CreateThread() which is also Microsoft (WinAPI) specific and is found in many Windows programs.
what, if anything, is the difference?
_beginthreadex
and CreateThread
are non-standard Microsoft/Windows specific functions.
_beginthread
has support for starting a thread in Managed Code which may be useful in a mixed environment.
CreateThread
is the native WinAPI call to create a thread. It's the call you'll find in classic Windows programs. A thread handle returned by this call gives you the ability to control the thread in different ways, for example, by calling SetThreadPriority() etc.
Using <thread>
is the, since C++11, standard way to do threading. It has most of what you will ever need - but lacks some platform specific support for dealing with the threads. Yet, a thread created by the standard library can return the native thread handle to enable prioritization etc. by using platform specific calls with that handle.
if there is a difference, when should one be used instead of the other?
Since you are learning threads and are not digging around in old code, you should definitely go with <thread>
. It'll probably take a very long time before you feel the need to use native calls to fiddle with the threads in a platform specific way - and if you do, you can still get the native handle.
Using <thread>
also makes your programs portable. In a Posix environment, the threading is usually done by Posix Threads (with a totally different API than the Windows API), yet by creating code that uses pure <thread>
calls you make porting your program a non-issue. It just works.
Upvotes: 2
Reputation: 17678
Stick with the first and standard way in C++ to create thread, i.e, using std::thread.
The second is Microsoft specific. I doubt that anyone would use it nowadays. See this: https://www.quora.com/When-do-we-write-include-process-h/answer/Sergey-Zubkov-1
Upvotes: 3