C++多线程编程(线程类)

简述

通过线程类来管理线程,实现业务逻辑与线程管理分离

源代码

接口类 SFRunnable.h

class SFRunnable
{
    public:
        virtual ~SFRunnable() {};
        virtual void Run() = 0;
};

线程类 SFThread.h

#ifndef __SFTHREAD_H__
#define __SFTHREAD_H__

#include <string>
#include <windows.h>
#include <process.h>

#include "SFRunnable.h"


class SFThread : public SFRunnable
{
private:
    explicit SFThread(const SFThread & rhs);//explicit

public:
    SFThread();
    SFThread(SFRunnable * pRunnable);
    SFThread(const char * ThreadName, SFRunnable * pRunnable = NULL);
    SFThread(std::string ThreadName, SFRunnable * pRunnable = NULL);
    ~SFThread(void);

    /**
      开始运行线程
      @arg bSuspend 开始运行时是否挂起
    **/
    bool Start(bool bSuspend = false);

    /**
      运行的线程函数,可以使用派生类重写此函数
    **/
    virtual void Run();

    /**
      当前执行此函数线程等待线程结束
      @arg timeout 等待超时时间,如果为负数,等待无限时长
    **/
    void Join(int timeout = -1);
    /**
      恢复挂起的线程
    **/
    void Resume();
    /**
      挂起线程
    **/
    void Suspend();
    /**
      终止线程的执行
    **/
    bool Terminate(unsigned long ExitCode);

    unsigned int GetThreadID();
    std::string GetThreadName();
    void SetThreadName(std::string ThreadName);
    void SetThreadName(const char * ThreadName);

private:
    static unsigned int WINAPI StaticThreadFunc(void * arg);//线程处理函数

private:
    HANDLE m_handle;//线程句柄
    SFRunnable * const m_pRunnable;//执行逻辑的指针
    unsigned int m_ThreadID;//线程ID
    std::string m_ThreadName;//线程name
    volatile bool m_bRun;//线程是否运行
};

#endif


/*
volatile:A volatile specifier is a hint to a compiler that an object may change its value in ways not specified by the language so that aggressive optimizations must be avoided.
*/

SFThread.cpp

#include "SFThread.h"

SFThread::SFThread(void) : m_pRunnable(
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值