一个线程封装类

简介:
class CThread
{
public:
        /**
         * Default Constructor
         */
        CThread()
        { 
            m_pThreadFunction = CThread::EntryPoint;
            m_runthread = FALSE;
        }

        /**
         * Default Destructor
         * also destroys the thread
         */
        ~CThread()
        {
            if ( m_hThread )
                Stop(true);                    //thread still running, so force the thread to stop!
        }
        /**
         * Starts the thread.
         * @param dwCreationFlags        the flags to use for creating the thread. see CreateThread() in the windows sdk.
         */
        DWORD Start(DWORD dwCreationFlags = 0)
        {
            m_runthread = true;
            m_hThread = CreateThread(NULL, 0, m_pThreadFunction, this, 0, &dwCreationFlags);
            m_dwExitCode = (DWORD)-1;

            return GetLastError();
        }

        /**
         * Stops the thread.
         *    
         * @param bForceKill        if true, the Thread is killed immediately
         */
        DWORD Stop ( bool bForceKill = false )
        {
            if ( m_hThread )
            {
                //尝试"温柔地"结束线程
                if (m_runthread == TRUE)
                    m_runthread = FALSE;        //first, try to stop the thread nice
                
                GetExitCodeThread(m_hThread, &m_dwExitCode);

                if ( m_dwExitCode == STILL_ACTIVE && bForceKill )
                {//强制杀死线程
                    TerminateThread(m_hThread, DWORD(-1));
                    m_hThread = NULL;
                }
            }

            return m_dwExitCode;
        }
        /**
         * Stops the thread. first tell the thread to stop itself and wait for the thread to stop itself.
         * if timeout occurs and the thread hasn't stopped yet, then the thread is killed.
         * @param timeout    milliseconds to wait for the thread to stop itself
         */
        DWORD Stop ( WORD timeout )
        {
            Stop(false);
            WaitForSingleObject(m_hThread, timeout);//等待一段时间
            return Stop(true);
        }

        /**
         * suspends the thread. i.e. the thread is halted but not killed. To start a suspended thread call Resume().
         */
        DWORD Suspend()
        {//挂起线程
            return SuspendThread(m_hThread);
        }

        /** 
         * resumes the thread. this method starts a created and suspended thread again.
         */
        DWORD Resume()
        {//恢复线程
            return ResumeThread(m_hThread);
        }

        /**
         * sets the priority of the thread.
         * @param priority    the priority. see SetThreadPriority() in windows sdk for possible values.
         * @return true if successful
         */
        BOOL SetPriority(int priority)
        {//设置线程优先级
            return SetThreadPriority(m_hThread, priority);
        }

        /**
         * gets the current priority value of the thread.
         * @return the current priority value
         */
        int GetPriority()
        {//获取线程优先级
            return GetThreadPriority(m_hThread);
        }

protected:

        /**
         * 子类应该重写此方法,这个方法是实际的工作线程函数
         */
        virtual DWORD ThreadMethod() = 0;
        
private:

        /**
         * DONT override this method.
         *
         * this method is the "function" used when creating the thread. it is static so that way
         * a pointer to it is available inside the class. this method calls then the virtual 
         * method of the parent class.
         */
        static DWORD WINAPI EntryPoint( LPVOID pArg)
        {
            CThread *pParent = reinterpret_cast<CThread*>(pArg);
            pParent->ThreadMethod();//多态性,调用子类的实际工作函数
            return 0;
        }
        
private:
    HANDLE    m_hThread;                    ///<Thread Handle    线程句柄
    DWORD    m_dwTID;                    ///<Thread ID    线程ID
    LPVOID    m_pParent;                    ///<this pointer of the parent CThread object
    DWORD    m_dwExitCode;                ///<Exit Code of the thread 线程退出码

protected:
    LPTHREAD_START_ROUTINE    m_pThreadFunction;    ///<工作线程指针
    BOOL    m_runthread;                ///<线程是否继续运行的标志
};
复制代码



本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/07/06/1236957.html,如需转载请自行联系原作者
目录
相关文章
|
8月前
|
安全 Java 开发者
【JAVA】封装多线程原理
Java 中的多线程封装旨在简化使用、提高安全性和增强可维护性。通过抽象和隐藏底层细节,提供简洁接口。常见封装方式包括基于 Runnable 和 Callable 接口的任务封装,以及线程池的封装。Runnable 适用于无返回值任务,Callable 支持有返回值任务。线程池(如 ExecutorService)则用于管理和复用线程,减少性能开销。示例代码展示了如何实现这些封装,使多线程编程更加高效和安全。
|
12月前
lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O
Lua的面向对象编程、协同线程与协同函数的概念和使用,以及Lua文件I/O操作的基本方法。
142 4
lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O
|
10月前
|
Java
【JavaEE】——多线程常用类
Callable的call方法,FutureTask类,ReentrantLock可重入锁和对比,Semaphore信号量(PV操作)CountDownLatch锁存器,
|
10月前
|
Java 程序员 调度
【JavaEE】线程创建和终止,Thread类方法,变量捕获(7000字长文)
创建线程的五种方式,Thread常见方法(守护进程.setDaemon() ,isAlive),start和run方法的区别,如何提前终止一个线程,标志位,isinterrupted,变量捕获
|
10月前
|
安全 Java API
【JavaEE】多线程编程引入——认识Thread类
Thread类,Thread中的run方法,在编程中怎么调度多线程
|
11月前
|
安全 Java
Java多线程集合类
本文介绍了Java中线程安全的问题及解决方案。通过示例代码展示了使用`CopyOnWriteArrayList`、`CopyOnWriteArraySet`和`ConcurrentHashMap`来解决多线程环境下集合操作的线程安全问题。这些类通过不同的机制确保了线程安全,提高了并发性能。
184 1
|
12月前
|
Java 开发者
在Java多线程编程中,创建线程的方法有两种:继承Thread类和实现Runnable接口
【10月更文挑战第20天】在Java多线程编程中,创建线程的方法有两种:继承Thread类和实现Runnable接口。本文揭示了这两种方式的微妙差异和潜在陷阱,帮助你更好地理解和选择适合项目需求的线程创建方式。
194 3
|
12月前
|
Java
在Java多线程编程中,实现Runnable接口通常优于继承Thread类
【10月更文挑战第20天】在Java多线程编程中,实现Runnable接口通常优于继承Thread类。原因包括:1) Java只支持单继承,实现接口不受此限制;2) Runnable接口便于代码复用和线程池管理;3) 分离任务与线程,提高灵活性。因此,实现Runnable接口是更佳选择。
226 2
|
12月前
|
Java
Java中多线程编程的基本概念和创建线程的两种主要方式:继承Thread类和实现Runnable接口
【10月更文挑战第20天】《JAVA多线程深度解析:线程的创建之路》介绍了Java中多线程编程的基本概念和创建线程的两种主要方式:继承Thread类和实现Runnable接口。文章详细讲解了每种方式的实现方法、优缺点及适用场景,帮助读者更好地理解和掌握多线程编程技术,为复杂任务的高效处理奠定基础。
171 2
|
12月前
|
Java 开发者
Java多线程初学者指南:介绍通过继承Thread类与实现Runnable接口两种方式创建线程的方法及其优缺点
【10月更文挑战第20天】Java多线程初学者指南:介绍通过继承Thread类与实现Runnable接口两种方式创建线程的方法及其优缺点,重点解析为何实现Runnable接口更具灵活性、资源共享及易于管理的优势。
244 1