C++一个简单的线程例子

下面是一个简单的线程例子,以后可以按照这个写。

.h文件:

#pragma once
#include

class CMyThread
{
public:
    CMyThread()
    {
        m_stopFlag = false;
        m_Handle = nullptr;
    }
    ~CMyThread()
    {
        CloseHandle(m_Handle);
    }

public:
    void InitHandle();
    void Start();
    void Stop();

    void setStopFlag(bool bol);
    bool getStopFlag();

private:
    handle_t    m_Handle;    
    bool        m_stopFlag;

private:
    static DWORD WINAPI ThreadProc(LPVOID lpParma);
};

.cpp文件:

#include "stdafx.h"
#include "MyThread.h"

void CMyThread::InitHandle()
{
    m_Handle = CreateThread(nullptr,0,ThreadProc,this,CREATE_SUSPENDED,nullptr);//CREATE_SUSPENDED,表示创建的线程先挂起,这个参数如果是0 ,表示立刻执行该线程
}

void CMyThread::Start()
{
    ResumeThread(m_Handle);
}

void CMyThread::Stop()
{
    SuspendThread(m_Handle);
}

void CMyThread::setStopFlag(bool bol)
{
    m_stopFlag = bol;
}

bool CMyThread::getStopFlag()
{
    return m_stopFlag;
}

DWORD WINAPI CMyThread::ThreadProc(LPVOID lpParma)
{
    CMyThread* pthis = static_cast(lpParma);

    while (true)
    {
        if (pthis->getStopFlag()) //推荐用这个方法退出
            break;

        OutputDebugString(L"abc\r\n");
        Sleep(1000);
    }
    return 0;
}

你可能感兴趣的:(C++一个简单的线程例子)