C语言 Windows 线程 - 调试工作版本不 - 尝试在线程启动时从线程获取值



我正在尝试获取线程的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_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.
    ...
}

最新更新