木其网络科技专业程序员代写http://www.xmsydw.com
程序员学历擅长经验网店链接
apenny硕士ASP.NET PHP 电子 通信设计 图像 编程 网络5年进入店铺
zheng_qianqian本科C语言 C++面向对象 Java5年进入店铺
guoguanl本科Java Web项目 JSP Hibernate Struts Mysql5年进入店铺

对 pthread 做的一个简陋封装

参考自 pthreadcc 库的 ThreadBase 类

用法:继承该类,重写 execute 方法,调用父类的 launchThread 方法启动线程

Thread.h

//
//  Thread.h
//  MinaCppClient
//
//  Created by yang3wei on 7/23/13.
//  Copyright (c) 2013 yang3wei. All rights reserved.
//

#ifndef __MinaCppClient__Thread__
#define __MinaCppClient__Thread__

#include <netdb.h>

class Thread {
public:
    Thread();
    ~Thread();
    
    void launchThread();
    
protected:
    virtual void* initialise();
    virtual void* execute();
    virtual void cleanUp();
    
private:
    pthread_t m_oThread;
    static void* threadMain(void* in_pArg);
};

#endif /* defined(__MinaCppClient__Thread__) */
Thread.cpp

//
//  Thread.cpp
//  MinaCppClient
//
//  Created by yang3wei on 7/23/13.
//  Copyright (c) 2013 yang3wei. All rights reserved.
//

#include "Thread.h"
#include <pthread.h>
#include <stdio.h>

Thread::Thread() {
//    printf("Thread::Thread()\n");
}

Thread::~Thread() {
//    printf("Thread::~Thread()\n");
}

void* Thread::initialise() {
//    printf("Thread::initialise()\n");
    return NULL;
}

void* Thread::execute() {
//    printf("Thread::execute()\n");
    return NULL;
}

void Thread::cleanUp() {
//    printf("Thread::cleanUp()\n");
}

void Thread::launchThread() {
//    printf("Thread::launchThread()\n");
    do {
        pthread_attr_t tmp_oThreadAttr;
        if (pthread_attr_init(&tmp_oThreadAttr) != 0) {
            printf("launchThread()->pthread_attr_init() error!\n");
            break;
        }
        if (pthread_attr_setdetachstate(&tmp_oThreadAttr, PTHREAD_CREATE_DETACHED) != 0) {
            printf("launchThread()->pthread_attr_setdetachstate() error!\n");
            pthread_attr_destroy(&tmp_oThreadAttr);
            break;
        }
        if (pthread_create(&m_oThread, &tmp_oThreadAttr, &(Thread::threadMain), this) != 0) {
            printf("launchThread()->pthread_create() error!\n");
            break;
        }
        printf("Launch receive thread successfully!\n");
    } while (0);
}

void* Thread::threadMain(void* in_pThread) {
//    printf("Thread::threadMain()\n");
    Thread* t_pThread = (Thread*)in_pThread;
    void* t_pRetVal;
    
    if ((t_pRetVal = t_pThread->initialise()) == NULL) {
        t_pRetVal = t_pThread->execute();
    }
    
    t_pThread->cleanUp();
    
    return t_pRetVal;
}


posted @ 2013-07-24 17:26  程序流程图  阅读(492)  评论(0编辑  收藏  举报
木其网络科技专业程序员代写http://www.xmsydw.com
程序员学历擅长经验网店链接
apenny硕士ASP.NET PHP 电子 通信设计 图像 编程 网络5年进入店铺
zheng_qianqian本科C语言 C++面向对象 Java5年进入店铺
guoguanl本科Java Web项目 JSP Hibernate Struts Mysql5年进入店铺