2010-01-05 700 views
3

我需要能夠暫停和恢復Windows C++應用程序中的主線程。我已經使用在C++中掛起並恢復主線程for Windows

handle = GetCurrentThread(); 
SuspendThread(handle); 

,然後其中應恢復

ResumeThread(handle); 

,同時暫停它的工作原理,恢復它沒有。我有其他線程暫停和恢復沒有問題,是否有什麼是不同的主線程。

我已經完成了很多使用C#和Java的線程工作,但這是我第一次在C++中完成任何工作,而且我發現它有點不同。

+2

是主線程試圖暫停和恢復自己。當線程暫停並且無法執行ResumeThread調用時,線程如何恢復。 – rerun 2010-01-05 18:22:27

+0

不,它調用SuspendThread本身,但稍後由另一個線程調用ResumeThread。在調試模式下,它顯示線程窗格上的掛起計數,當掛起被調用時它會增加1,但在調用恢復時不會減少一次。 – 2010-01-05 18:25:21

+0

ResumeThread()是否返回負值,如果是,GetLastError()會返回什麼? – 2010-01-05 18:33:09

回答

12

您使用的是「處理」值從GetCurrentThread有()在其他線程?如果是,那是一個僞造價值。要得到一個真正的線程句柄,可以使用DuplicateHandle或者試試

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

+0

謝謝,這工作。 – 2010-01-05 18:39:09

2

獲得相同結果的最簡單方法是CreateEvent,並且其上有主線程WaitForSingleObject,然後將其從另一個線程中以SetEvent喚醒。

+0

請記住,只要主線程暫停或等待,消息泵將不會被泵送。除此之外,最明顯的結果是GUI將無響應。 – 2010-01-05 18:34:28

+0

不會掛起主線程有相同的結果嗎? – 2010-01-05 18:38:12

+0

這不是我說的嗎? :) – 2010-01-05 18:50:20

2

而且,下面是一個示例,顯示了一些人之前建議的內容。

#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); 
} 
相關問題