Thomas Mccaffery
Thomas Mccaffery

Reputation: 395

Using _beginthreadex/_endthreadex functions

I checked the source code of a project with an analyzer. I am new to C++.

It tells me that I should use Use _beginthreadex/_endthreadex functions instead of CreateThread/ExitThread functions

std::unique_ptr<Thread> Thread::Create(CreationParameters params,
                                   std::function<void()> start_routine) {
auto start_data = new ThreadStartData({std::move(start_routine)});
HANDLE handle =
  CreateThread(NULL, params.stack_size, ThreadStartRoutine, start_data,
               params.create_suspended ? CREATE_SUSPENDED : 0, NULL);
if (handle == INVALID_HANDLE_VALUE) {

void Thread::Exit(int exit_code) { ExitThread(exit_code); }

Upvotes: 0

Views: 548

Answers (1)

Anders
Anders

Reputation: 101764

It really depends on what you are doing. If you are only calling Windows API functions in the new thread then CreateThread is fine but if you are calling C standard library functions in the thread then you are supposed to use _beginthreadex. _beginthreadex will call CreateThread internally but it might also allocate and initialize some per-thread CRT state.

I see someone in the comments claiming that the CRT no longer assigns CRT state this way. I don't know if that's true and either way, it is a implementation detail and could change depending on the compiler version. _beginthreadex will never be wrong so there is no reason not to use it.

Upvotes: 2

Related Questions