ACE线程管理

本文介绍了如何使用ACE库进行线程管理,包括通过ACE_Thread_Manager类和ACE_Task_Base类创建线程的方法。示例代码展示了如何传递参数、启动线程以及使用消息队列进行线程间通信。此外,还讨论了ACE_Task的使用,包括消息队列的管理,如设置高水位标记、关闭消息队列等操作。
摘要由CSDN通过智能技术生成

运用ACE_Thread_Manager类创建线程

    创建线程需要要解决两个问题,一是调用线程函数,二是提供一个途径让线程能够访问到外部传递过来的参数。下面的代码演示了基本的用法:
#include <stdexcept>
#include "ace/ACE.h"
#include "ace/Log_Msg.h"
#include "ace/Thread_Manager.h"
#include <map>
#include <string>
#include <iostream>
using namespace std;

class ThreadArg {
public:

    ThreadArg() {
    }
private:
    string arg0;
public:

    void setArg0(string value) {
        arg0 = value;
    }

    string getArg0() const {
        return arg0;
    }
};

class MyThread {
public:
    static void* run_svc(void* arg) {
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t) MyThread running/n")));
        ThreadArg* pArg = static_cast<ThreadArg*> (arg);
        cout << pArg->getArg0() << endl;
    }
};

int ACE_TMAIN(int, ACE_TCHAR *[]) {
    ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t) Main Thread running/n")));
    ThreadArg threadArg;
    threadArg.setArg0("ok");
    ACE_thread_t threadID;
    if (ACE_Thread_Manager::instance()->spawn(MyThread::run_svc, static_cast<void*>(&threadArg),
            THR_DETACHED | THR_SCOPE_SYSTEM, &threadID) == -1) {
        throw std::runtime_error("can't create a new thread in SnapShotReqWiater::run method");
    }
    ACE_Thread_Manager::instance()->wait();
    return 0;
}

    使用ACE_Thread_Manager::spawn方法创建线程,第一个参数是线程的函数,第二个是一个对象指针,里面存放了参数,其他的参数请参考文档
http://www.dre.vanderbilt.edu/Doxygen/5.7.5/html/ace/a00676.html#a36262a470e556182f5d69c4de7cfeaa1
    wait方法等待线程运行完毕后才会返回。

运用ACE_Task_Base类创建线程

    前面一种方法不够面向对象,线程需要成为一个对象,并且参数可以通过设置属性的形式自然的进行。下面的例子来自于<<ACE Programmers Guide>>,略作修改&

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值