我正在尝试获取线程的ID,以便存储在线程列表中。
为此,我启动了一个线程,该线程的指针指向一个存储线程ID的long
。线程函数执行后,应该立即存储线程ID。一旦存储了ID,启动函数就应该能够继续。
此代码似乎只在调试模式下工作,但在发布模式下挂起。我用的是Visual C++ 2008 Express。
我需要这些代码才能在Windows XP上运行,所以很遗憾我不能简单地使用GetThreadId
,因为它只在Windows Server 2003和更新版本上受支持。
thread_wrapper* spawn_thread(void *entryPoint, void *params)
{
thread_wrapper *newThread = calloc(1, sizeof(thread_wrapper));
_beginthread(spawned_thread_wrapper_func, 0, &newThread->_win32ThreadID);
while (newThread->_win32ThreadID == 0) ; // Hangs here in Release mode
... // Safely add thread to list using critical section
return newThread;
}
void spawned_thread_wrapper_func(void *params)
{
long *outThreadIDPtr = (long *)params;
*outThreadIDPtr = GetCurrentThreadId();
// spawn_thread function should now be able to add thread to list
// but still hangs on while waiting loop in Release mode.
// Works fine in Debug mode.
...
}
这里出什么事了?
最佳答案
如果希望在该成员变量中包含当前线程id,这是使用_beginthreadex()
的一种方法。该api使您能够更好地控制线程创建过程,并在需要时提供一个用于检测线程终止的等待句柄。注意,thread proc的原型和下面的实现更改非常重要。
thread_wrapper* spawn_thread(void *entryPoint, void *params)
{
thread_wrapper *newThread = calloc(1, sizeof(thread_wrapper));
// hThread is an OS thread handle you can wait on with
// wait functions like WaitForSingleObject.
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0,
spawned_thread_wrapper_func, newThread,
CREATE_SUSPENDED, &newThread->_win32ThreadID);
// TODO: add new thread (which is created, but not started yet)
// to your list.
// now resume the thread.
ResumeThread(hThread);
// if you don't need this any longer, close it, otherwise save it
// somewhere else (such as *before* the resume above, you can save
// it as a member of your thread_wrapper). No matter what, you have
// to close it eventually
// CloseHandle(hThread);
return newThread;
}
// note return value difference when using _beginthreadex.
unsigned int _stdcall spawned_thread_wrapper_func(void *params)
{
thread_wrapper* p = params; // note: with MS you may have to cast this.
// spawn_thread function should now be able to add thread to list
// but still hangs on while waiting loop in Release mode.
// Works fine in Debug mode.
...
}
关于c - Windows线程-调试版本不发布-尝试在启动时从线程获取值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18669046/