Linux下的主動對象類的實現

來源:互聯網
上載者:User

#pragma once
#include <pthread.h>
class ThreadWrapper
{
public:
    virtual ~ThreadWrapper();
    static void EnterFunc(void *p);
    int Open();
    int Close();
    bool TestCancel();
    void Wait();
    virtual void Svc();

protected:
    ThreadWrapper();

private:
    bool m_stillOpen;
    int m_threadNum;
    pthread_t m_handle;
};

 

 

*************************************************

#include "ThreadWrapper.h"

ThreadWrapper::ThreadWrapper()
: m_stillOpen(false)
{}

ThreadWrapper::~ThreadWrapper()
{
    if(m_stillOpen)
    {
        Close();
        Wait();
    }
}
/*
Functional: The enter function of the thread.
*/
void ThreadWrapper::EnterFunc (void *p)
{
    ThreadWrapper* bp = static_cast <ThreadWrapper*> (p);
     bp->Svc();
}

/*
Functional: Create the thread.
*/
int ThreadWrapper::Open ()
{
    m_threadNum = threadNum;
    int ret = pthread_create(&m_handle, NULL, EnterFunc, this);
    if (ret != 0)
   {
       return -1;
    }

    m_stillOpen = true;
    return 0;
}

 

int ThreadWrapper::Close()
{
    pthread_cancel(m_handle);
    m_stillOpen = false;
    return 1;
}

 

void ThreadWrapper::TestCancel()
{
     pthread_testcancel();
}

 

void ThreadWrapper::Wait()
{
    pthread_join(m_handle, NULL);
    m_stillOpen = false;
}

void ThreadWrapper::Svc()
{}

 

此主動對象的用法如下:

1:先定義主動對象類,派生自ThreadWrapper即可,然後實現Svc()虛方法

class Sample : Public ThreadWrapper

{

public:

    virtual void Svc()

    {

       ...// add anything you wanna do, and TestCancel() can be positioned somewhere 

    }

}

2:定義Sample對象,然後open.....

Sample sample;

sample.open();  // 此句執行後線程就開始執行了,即Sample::Svc()開始執行

......

sample.close(); // 主動關閉線程

sample.wait();  // 等待Sample對象的線程執行完畢

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.