thread

33 篇文章 0 订阅
// 自己简单封装的thread类
// thread.h

#ifndef  _THREAD_SPECIFICAL_H_
#define  _THREAD_SPECIFICAL_H_

#include <Windows.h>

static UINT WINAPI threadFunc(LPVOID pParam);

class Thread
{
    friend UINT WINAPI threadFunc(LPVOID pParam);
public:
    Thread();
    virtual ~Thread();
    int start(void * = NULL);
    // 调用wait()之后,主线程必须等待子线程结束之后才结束
    void* wait();
    // 停止线程
    void stop();
    // 分离线程:当子线程结束之后,系统自动清理线程所占用的资源,对于并发性很高的程序,一般都设置成分离线程
    void detach();
    static void sleep(UINT);
protected:
    virtual void* run(void*) = 0;
private:
    HANDLE threadHandle;
    bool started;
    bool detached;
    void *param;
    UINT threadID;
};

#endif

// thread.cpp

#include <process.h>
#include "thread.h"


UINT WINAPI threadFunc(LPVOID pParam)
{
    Thread* thread = (Thread*)pParam;
    return (UINT)thread->run(thread->param);
}


Thread::Thread()
{
    started = false;
    detached = false;
}


Thread::~Thread()
{
    stop();
}


int Thread::start(void * pParam/* = NULL */)
{
    if(!started)
    {
        param = pParam;
        if(threadHandle = (HANDLE)_beginthreadex(NULL, 0, threadFunc, this, 0, &threadID))
        {
            if(detached)
                CloseHandle(threadHandle);
            started = true;
        }
    }
    return started;
}


void* Thread::wait()
{
    DWORD status = (DWORD)NULL;
    if(started && !detached)
    {
        WaitForSingleObject(threadHandle, INFINITE);
        GetExitCodeThread(threadHandle, &status);
        CloseHandle(threadHandle);
        detached = true;
    }
    return (void*)status;
}


void Thread::detach()
{
    if(started && !detached)
        CloseHandle(threadHandle);
    detached = true;
}


void Thread::stop()
{
    if(started && !detached)
    {
        TerminateThread(threadHandle, 0);
        CloseHandle(threadHandle);
        detached = true;
    }
}


void Thread::sleep(UINT delay)
{
    ::Sleep(delay);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值