运用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>>,略作修改&