写一个线程类,可以直接调用类的方法执行,欢迎大家拍砖!

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
class LazyThread
{
public:
    LazyThread()
    {
        m_bAlive    = 0;
        m_thread    = 0;
    }
    ~LazyThread()
    {
    }

    virtual int thread_proc(){};

    static void* init_thread_proc(void* powner)
    {
        LazyThread* pthis = (LazyThread*)powner;
        if(pthis)
        {
            pthis->m_bAlive = 1;
            pthis->thread_proc();
        }

        return NULL;
    }

    virtual int start()
    {
        if(!m_bAlive)
        {
            pthread_create(&m_thread, NULL, init_thread_proc, this);//m_handle = CreateThread(NULL, 0, LazyThread::init_thread_proc, this, 0, 0);
            return 0;
        }

        return -1;
    }

    virtual void stop()
    {
        m_bAlive = 0;
        pthread_join(m_thread,NULL);
    }

    virtual int join()
    {
        return pthread_join(m_thread,NULL);
    }

    virtual int detach()
    {
        return pthread_detach(m_thread);
    }
protected:
    int            m_bAlive;
    pthread_t    m_thread;
};

template<class T>
class lazythreadex:public LazyThread{
public:
    lazythreadex()
    {
        m_powner        = NULL;
        m_pcallback_proc    = NULL;
    }

    ~lazythreadex()
    {
    }

    typedef int (T::*callback)();

    virtual int init_class_func(T* powner, callback class_func)
    {
        m_powner = powner;
        m_pcallback_proc = class_func;

        return 0;
    }

    virtual int thread_proc()
    {
        if(m_pcallback_proc && m_powner)
        {
            return (m_powner->*m_pcallback_proc)();
        }

        return -1;
    }

protected:
    callback        m_pcallback_proc;
    T*            m_powner;
};

 class HelloPrinter
 {
 public:
    HelloPrinter()
    {
        m_ncount = 100;
    }


     int print_proc()
     {
         for(int i = 0; i < m_ncount; i++)
         {
             printf("%d hello!\n", i);
             sleep(1);
         }

         return 0;
     }

protected:
    int m_ncount;
 };
int main(int argc, char** args)
{
    lazythreadex<HelloPrinter>    print_thread;
    HelloPrinter printer;
    print_thread.init_class_func(&printer, &HelloPrinter::print_proc);
    print_thread.start();
    print_thread.join();
    print_thread.stop();
    return 0;
}

懒熊工作室
94 声望4 粉丝