0

我正在尝试获取线程的 ID 以存储在线程列表中。

为此,我将启动一个带有指向long将存储线程 ID 的指针的线程。线程 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.

    ...
}

这里出了什么问题?

4

1 回答 1

3

如果您想要该成员变量中的当前线程 ID,这是使用_beginthreadex(). 该 api 使您可以更好地控制线程创建过程,以及在需要时检测线程终止的可等待句柄。请注意,线程 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.

    ...
}
于 2013-09-07T02:44:07.640 回答