一.创建线程函数
常用的创建线程的函数是CreateThread,还有MFC中的AfxBeginThread方法.另一种函数是_beginthreadex,
其实它在内部调用了CreateThread,在调用之前_beginthreadex做了很多的工作,从而使得它比CreateThread更
安全.所以一般使用_beginthreadex来创建线程.于是以下使用_beginthreadex函数来创建线程类.
二.线程类示例
1.Thread.h文件如下:
#ifndef _THREAD_H__
#define _THREAD_H__
#include <process.h>
#include <windows.h>
class CThread
{
public:
public:
CThread();
virtual ~CThread();
BOOL StartThread(); //开始线程
BOOL SuspendThread(); //挂起线程
virtual BOOL Run(); //线程的入口
BOOL StopThread(); //等待线程退出再返回
static unsigned __stdcall start_address( void * obj);
public:
HANDLE m_hthread; //线程句柄
HANDLE m_hEventSuspend; //用于标识线程是工作,还是挂起状态
BOOL m_status; //线程状态,FALSE表示线程退出状态,TRUE表示未提出状态
unsigned m_thrdaddr;
};
#endif/*_THREAD_H__*/
2.Thread.cpp文件如下:
#include "Thread.h"
CThread::CThread()
{
m_hEventSuspend = CreateEvent(0,TRUE,FALSE,NULL);//创建事件句柄,且为非激发状态
m_status = TRUE;
//创建线程
m_hthread = (HANDLE)_beginthreadex(NULL,0,CThread::start_address,this,0,&m_thrdaddr);
}
CThread::~CThread()
{
CloseHandle(m_hEventSuspend);
CloseHandle( m_hthread );
}
BOOL CThread::StartThread()
{
return SetEvent(m_hEventSuspend);
}
BOOL CThread::SuspendThread()
{
return ResetEvent(m_hEventSuspend);
}
BOOL CThread::Run()
{
return TRUE;
}
BOOL CThread::StopThread()
{
m_status = FALSE;//将线程状态置为退出
StartThread(); //把线程唤醒,以免挂死在休眠处
WaitForSingleObject(m_hthread,INFINITE); //等待线程退出
return TRUE;
}
unsigned __stdcall CThread::start_address( void * obj)
{
CThread* pthread = static_cast<CThread*>(obj);
while(pthread->m_status)
{
WaitForSingleObject(pthread->m_hEventSuspend,INFINITE);//控制挂起,运行
//如果自动退出
if (!pthread->Run())
break;
}
_endthreadex(0);
return 0;
}
三.线程类的使用
1. 新建一个win32控制台工程,代码如下:
#include "Thread.h"
#include <iostream>
#include <conio.h>
using namespace std;
class CMyThread:public CThread
{
public:
BOOL Run()
{
cout<<"hello!"<<endl;
Sleep(5000);
return TRUE;
}
};
int main(int argc,char *argv[])
{
//创建线程
CMyThread mythread;
//让线程启动
mythread.StartThread();
//按任意键,线程挂起
_getch();
mythread.SuspendThread();
cout<<"thread suspend"<<endl;
//接任意键,线程停止
_getch();
mythread.StopThread();
cout<<"thread stop"<<endl;
//按任意键,程序退出
_getch();
return 0;
}