繁体   English   中英

Windows线程-调试版本不发布-尝试在启动时从线程获取值

[英]Windows Threading - debug works release does not - attempting to get value from thread when it starts

我正在尝试获取要存储在线程列表中的线程的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可让您对线程创建过程进行更多控制,并在需要时提供用于检测线程终止的等待句柄。 请注意,线程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.

    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM