#include "windows.h"
#include "iostream.h"//线程消息
#define THR_SUSPEND WM_USER+1class MyThread
{
public:
MyThread(char* szName);
virtual ~MyThread();
static int CALLBACK ThreadFunc(MyThread* pParam);
void Run();
void Stop();
void WaitFor();
inline DWORD GetThreadID(){ return m_id; }
private:
char m_name[20];
HANDLE m_handle;
DWORD m_id;
void Refresh(int index);
};MyThread::MyThread(char* szName):m_handle(INVALID_HANDLE_VALUE)
{
m_handle=CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)ThreadFunc,
this,
CREATE_SUSPENDED,
&m_id);
strcpy(m_name,szName);
}MyThread::~MyThread()
{
CloseHandle(m_handle);
}int CALLBACK MyThread::ThreadFunc(MyThread* pParam)
{
static MyThread *pThis=pParam;
static int i=0;
static MSG msg;
while(1)
{
if(GetMessage(&msg,NULL,0,0))
{
switch (msg.message)
{
case THR_SUSPEND:
pThis->Stop();
break;
default:
break;
}
}
pThis->Refresh(i++);
}
return 0;
}void MyThread::Refresh(int index)
{
cout<<index<<endl;
}void MyThread::Run()
{
ResumeThread(m_handle);
}void MyThread::Stop()
{
SuspendThread(m_handle);
}void MyThread::WaitFor()
{
WaitForSingleObject(m_handle,200);
}main()
{
MyThread mthr("thread1");
while(1)
{
cout<<"resume thread(y/n):";
char ci;
cin>>ci;
if((ci=='n')||(ci=='N'))
{
PostThreadMessage(mthr.GetThreadID(),THR_SUSPEND,0,0);
}
else 
{
mthr.Run();
}
}
// mthr.Run();
// mthr.WaitFor();
return 0;
}

解决方案 »

  1.   

    1.
    int CALLBACK MyThread::ThreadFunc(MyThread* pParam)改为
    DWORD WINAPI MyThread::ThreadFunc(LPVOID lpParameter);2.
    试试static MSG msg 改为 MSG msg;3.
    查看PostThreadMessage(mthr.GetThreadID(),THR_SUSPEND,0,0)返回值是不是faile.
      

  2.   

    to icelight(icelight)
    非常感谢,好象并不是你上面所说的问题,我跟踪程序到了线程函数内部,发现while循环中执行完if就退出了,如果把pthis->refresh()放到if语句前面就可以执行一次输出0,接下来执行完if语句就退出了,不知什么原因,还望赐教。
      

  3.   

    我觉得你要重点看一下GetMessage函数在MSDN中的说明,加上一些有效性的
    判断,看看是不是它发生的异常!
      

  4.   

    我把它解决了,原来这样就可以了,非常感谢二位,每人加10分,呵呵:)
                      if(PeekMessage(&msg,NULL,0,0,0))
    {
    GetMessage(&msg,NULL,0,0);
    switch (msg.message)
    {
    case THR_SUSPEND:
    pThis->Stop();
    break;
    default:
    break;
    }
    }
    pThis->Refresh(i++);
      

  5.   

    GetMessage最好不要这样用,请看msdn里面怎么说
    Warning  Because the return value can be nonzero, zero, or -1, avoid code like this:while (GetMessage( lpMsg, hWnd, 0, 0)) ... 
    详细情况请看MSDN,我的修改如下
    if(GetMessage(&msg,NULL,0,0) > 0)
    {
    switch (msg.message)
    {
    case THR_SUSPEND:
    pThis->Stop();
    break;
    default:
    printf("msg.message is %d\r\n", msg.message);  //看看是不是收到其它消息退出了线程
    break;
    }
    }
    经我测试,你的代码没有问题,能正常运行,只是你挂起线程(输入了"n")以后一定要输入"y",恢复线程执行以后才能看到输出,否则,线程都被挂起来了,怎么执行:)