links77
links77

Reputation: 1454

Why does C++ thread class create two threads?

I am running Visual C++ 2013 and I notice that creating a thread with the std::thread class spawns two threads. Is this by design? If so, what is the reason for this?

When I use _beginthreadex() it only spawns one thread as I would expect.

unsigned int __stdcall Func(void*)
{
    unsigned int i = 0;
    while (i < 1000000000)
    {
        ++i;
    }
    return i;
}

int wmain()
{
    thread doStuff(Func, nullptr);
    auto id = doStuff.get_id();
    doStuff.join();
}

EDIT 1

When I put a breakpoint on doStuff.join() I see the following output. The id variable matches the 55760 thread. When I use _beginthreadex() I do not get that extra thread "ntdll.dll thread".

EDIT 2

Here is the call stack with symbols loaded.

ThreadTest.exe!wmain() Line 21
ThreadTest.exe!__tmainCRTStartup() Line 623
ThreadTest.exe!wmainCRTStartup() Line 466
kernel32.dll!@BaseThreadInitThunk@12()
ntdll.dll!___RtlUserThreadStart@8()
ntdll.dll!__RtlUserThreadStart@8()

Upvotes: 0

Views: 387

Answers (1)

Mustafa Chelik
Mustafa Chelik

Reputation: 2184

Main Thread is obvious. It's your main thread. When you create a thread, only one thread will be created. The msvcr* thread is Microsoft C Runtime Library. I don't think you can control it but don't mind it. Your code works as you expect.

Upvotes: 1

Related Questions