在分析safmq线程类时,觉得很好用,就模仿着写了一个。
类的定义如下:
.h文件内容如下
01 | #pragma once |
02 | #include <windows.h> |
03 | /**************************************************************** |
04 | * 文件名:Thread.h |
05 | * 功能:线程类定义,提供线程基类 |
06 | * 作者: |
07 | * 时间:2012-2-18 |
08 | *****************************************************************/ |
09 | class Thread |
10 | { |
11 | public : |
12 | Thread( void ); |
13 | ~Thread( void ); |
14 |
15 | void start(); //线程启动 |
16 | void stop(); //线程关闭 |
17 |
18 | protected : |
19 | virtual void * run() = 0; //线程运行 |
20 | friend unsigned long _stdcall _thd_start( void *param); //友元函数 |
21 |
22 | private : |
23 | HANDLE _thread; //线程句柄 |
24 | bool m_bStop; //线程是否需要停止 |
25 | unsigned long m_threadId; //线程ID |
26 |
27 | |
28 | }; |
.cpp文件格式如下
01 | #include "StdAfx.h" |
02 | #include "Thread.h" |
03 |
04 |
05 | /* |
06 | *函数名:_thd_start |
07 | *功能:线程入口函数 |
08 | *参数:param Thread的this指针 |
09 | */ |
10 | unsigned long _stdcall _thd_start( void * param) //线程函数的定义有固定的规则 |
11 | { |
12 | return ( long )((Thread*)param)->run(); |
13 | } |
14 |
15 |
16 | Thread::Thread( void ) |
17 | { |
18 | m_bStop = false ; |
19 | m_threadId = 0; |
20 | } |
21 |
22 |
23 | Thread::~Thread( void ) |
24 | { |
25 | stop(); |
26 | } |
27 |
28 | void Thread::start() |
29 | { |
30 | _thread = ::CreateThread(NULL, 0, _thd_start, this , 0, &m_threadId); //线程创建后立即运行 |
31 | } |
32 |
33 |
34 | void Thread::stop() |
35 | { |
36 | ::CloseHandle(_thread); |
37 | } |
使用方法如下:
01 | #include "stdafx.h" |
02 | #include "Thread.h" |
03 | #include <iostream> |
04 |
05 | using namespace std; |
06 |
07 | class TestCustomThread : public Thread |
08 | { |
09 | protected : |
10 | void * run(); |
11 | }; |
12 |
13 | void * TestCustomThread::run() |
14 | { |
15 | for ( int i = 0; i < 500; i++) |
16 | { |
17 | ::Sleep(200); |
18 | cout<<i<< " " <<endl<<flush; |
19 | } |
20 |
21 | return NULL; |
22 | } |
23 |
24 | int _tmain( int argc, _TCHAR* argv[]) |
25 | { |
26 | TestCustomThread customThread; |
27 |
28 | customThread.start(); |
29 |
30 | |
31 | getchar (); |
32 | return 0; |
33 | } |
如果我们想要定义自己的线程类,继承Thread类即可,并重写run()函数。