简体   繁体   English

在C ++ for Windows中挂起并恢复主线程

[英]Suspend and resume the main thread in C++ for Windows

I need to be able to suspend and resume the main thread in a Windows C++ app. 我需要能够在Windows C ++应用程序中暂停和恢复主线程。 I have used 我用过

handle = GetCurrentThread();
SuspendThread(handle);

and then where is should be resumed 然后应该恢复到哪里

ResumeThread(handle);

while suspending it works, resuming it does not. 暂停它工作,恢复它没有。 I have other threads that are suspended and resumed with no problems, is there something that is different with the main thread. 我有其他线程被暂停和恢复没有问题,是否有一些与主线程不同的东西。

I have done a lot of threading working in C# and Java but this is the first time I have done any in C++ and I'm finding it to be quite a bit different. 我已经在C#和Java中完成了很多线程工作,但这是我第一次用C ++完成任务,我发现它有点不同。

Are you using the "handle" value you got from GetCurrentThread() in the other thread? 你在另一个线程中使用GetCurrentThread()获得的“句柄”值吗? If so that is a psuedo value. 如果是这样,那就是伪造的价值。 To get a real thread handle either use DuplicateHandle or try 要获得真正的线程句柄,请使用DuplicateHandle或尝试

HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());

GetCurrentThread returns a "pseudo handle" that can only be used from the calling thread. GetCurrentThread返回一个只能在调用线程中使用的“伪句柄”。 Use DuplicateHandle to create a real handle that another thread can use to resume the main thread. 使用DuplicateHandle创建一个真正的句柄,另一个线程可以用来恢复主线程。

See http://msdn.microsoft.com/en-us/library/ms683182%28VS.85%29.aspx 请参阅http://msdn.microsoft.com/en-us/library/ms683182%28VS.85%29.aspx

获得相同结果的最简单方法是CreateEvent并在其上有主线程WaitForSingleObject ,然后从另一个线程用SetEvent唤醒它。

And, here's an example that shows what some of the folks have suggested before. 而且,这里有一个例子,显示了一些人之前的建议。

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <process.h>

HANDLE g_hMainThread;
void TheThread(void *);

int _tmain(int argc, _TCHAR* argv[])
{
    g_hMainThread = OpenThread(THREAD_ALL_ACCESS,
                               FALSE,
                               GetCurrentThreadId());
    printf( "Suspending main thread.\n" );
    _beginthread(TheThread, 0, NULL);
    SuspendThread(g_hMainThread);
    printf( "Main thread back in action.\n" );
    return 0;
}

void TheThread(void *)
{
    DWORD dwStatus = ResumeThread(g_hMainThread);
    DWORD dwErr = GetLastError();
    printf("Resumed main thread - Status = 0x%X, GLE = 0x%X.\n",
           dwStatus,
           dwErr );
}

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

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