Tah*_*lil 0 c++ winapi multithreading
我称之为提到的Windows API.但它返回的是与返回的id不同的线程ID _beginthreadex.我的代码如下,
ThreadTest *_threadTest = new ThreadTest();
Thread *_thread = new Thread(StartRoutineForThread,_threadTest);
Run Code Online (Sandbox Code Playgroud)
Thread类的构造函数是,
ThreadWin::ThreadWin(void * (*_startRoutine)(void *), void * _argument, bool _isJoinable)
{
unsigned int _threadAddress;
unsigned int threadID = _beginthreadex(
NULL,
0,
(unsigned int (__stdcall *)(void *))_startRoutine,
_argument,
0,
&_threadAddress
);
}
Run Code Online (Sandbox Code Playgroud)
StartRoutineForThread 作为线程的启动例程的函数如下,
void* StartRoutineForThread(void* _argument)
{
ThreadTest *_threadTest = (ThreadTest*)_argument;
_threadTest->Run();
return NULL;
}
void ThreadTest::Run()
{
this->threadID = ::GetCurrentThreadId();
}
Run Code Online (Sandbox Code Playgroud)
现在在类的构造函数中Thread,变量threadID的值不同于我从函数得到的类ThreadTest变量threadID的Run值.但是这个Run函数是从我创建线程时指定的函数调用的.所以该Run函数在我创建的同一个线程下运行.但那么为什么GetCurrentThreadId()返回的价值不同于返回的价值_beginthreadex呢?
好吧,_beginthreadex不返回线程ID.线程id存储在_threadAddress,最后一个参数_beginthreadex.它的返回值是线程句柄(如CreateThread),而不是id.