线程如何关闭测试

来源:互联网 发布:怎么用c语言表白 编辑:程序博客网 时间:2024/04/29 17:03

#include <stdio.h>
#include <windows.h>
#include <iostream>
#include <process.h>
using namespace std;

bool flag;
DWORD idThread1;
DWORD idThread2;

#define MY_MSG WM_USER+100

DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data
{
 //Sleep(500);
 while (true)
 {
  cout << "亲,线程1在努力加油"<<endl;
/*  bool bbreak = false;
  MSG msg;
  while(GetMessage(&msg,0,0,0)) //get msg from message queue
   {
     switch(msg.message)
            {
    case MY_MSG:
     bbreak = true;
     cout << "亲,线程1断开了吗?"<<endl;
     break;
    default:
     break;
    }
   
   }
  if (bbreak)
   break;*/
  Sleep(1);
 }
 return 0;
}

DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data
{
 while (true)
 {
  cout << "亲,线程2在努力加油"<<endl;
  bool bbreak = false;
  MSG msg;
  //if(GetMessage(&msg,NULL,0,0)) //get msg from message queue
  if (PeekMessage(&msg, NULL, NULL,NULL,PM_REMOVE))
   {
     switch(msg.message)
            {
    case MY_MSG:
     bbreak = true;
     cout << "亲,线程2断开了吗?"<<endl;
     break;
    default:
     //cout << "亲,线程2跳出循环了吗?"<<endl;
     break;
    }
   
   }
  //cout << "亲,线程2吗?"<<endl;
  if (bbreak)
   break;
  Sleep(1);
 }
 return 0;
}

int main()
{
 HANDLE hThread2;
 hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,&idThread2);

 HANDLE hThread1;
 hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,&idThread1);
 Sleep(50);

 CloseHandle(hThread1);
 CloseHandle(hThread2);
 
 cout << "关闭句柄"<<endl;
 Sleep(50);
 cout << "***************************************"<<endl;

 //Sleep(500);
 //PostMessage(idThread1, );
 PostThreadMessage(idThread2,MY_MSG,NULL,NULL);
 cout << "post线程消息"<<endl;
 Sleep(50);
 cout << "///////////////////////////////////////"<<endl;

 return 0;
}