ICE提供了一個跨平臺的c++ middleware,包含在源碼的include/IceUtil中。IceUtil中包含的主要類如下圖所示:
這些類主要提供了3類跨平臺的基礎功能:
1. SmartPoint / SharedPtr 功能。 Shared 中包含了__incRef() 和 __decRef()的方法。並且當 __decRef中的引用計數爲0時會delete this.
Handle在Constructor 和 Destructor 中會調用Shared 的 __incRef() 和 __decRef()方法。如下所示:
#include <iostream>
#include <IceUtil/Handle.h>
#include <IceUtil/Shared.h>
using namespace std;
using namespace IceUtil;
class MyShared : public Shared
{
public:
MyShared()
{
cout << "In function " << __FUNCTION__ << endl;
}
virtual ~MyShared()
{
cout << "In function " << __FUNCTION__ << endl;
}
};
Handle<MyShared> GetMyShared()
{
Handle<MyShared> mySharedHandle = new MyShared();
Handle<MyShared> mySharedHandle2 = mySharedHandle;
return mySharedHandle2;
}
void TestMyShared()
{
Handle<MyShared> shared = GetMyShared();
cout << "End of function " << __FUNCTION__ << endl;
}
int main()
{
TestMyShared();
cout << "End of function " << __FUNCTION__ << endl;
return 0;
}
2. 線程以及同步機制:ICE提供了線程(Thread),互斥鎖(Mutex)和條件變量(Cond)用於多線程的處理,如下示例所示:
#include <iostream>
#include <IceUtil/Thread.h>
#include <IceUtil/Cond.h>
using namespace std;
using namespace IceUtil;
Mutex mutex;
Cond cond;
class MyThread : public Thread
{
public:
virtual void run()
{
Mutex::Lock lock(mutex);
cout << "In function " << __FUNCTION__ << " singled with tid " <<
this->getThreadControl().id() << endl;
cond.signal();
}
};
int main()
{
ThreadPtr thread = new MyThread();
thread->start();
// wait for thread execute
{
Mutex::Lock lock(mutex);
cond.wait(lock);
}
cout << "Cond wait in function " << __FUNCTION__ << endl;
thread->getThreadControl().join();
return 0;
}
3. Monitor封裝了Cond用於喚醒(所有)等待的線程,如下示例:
#include <iostream>
#include <IceUtil/Thread.h>
#include <IceUtil/Monitor.h>
using namespace std;
using namespace IceUtil;
Monitor<Mutex> monitor;
class MyThread : public Thread
{
public:
virtual void run()
{
Monitor<Mutex>::Lock lock(monitor);
monitor.wait();
cout << "In function " << __FUNCTION__ << endl;
}
};
int main()
{
ThreadPtr thread = new MyThread();
thread->start();
{
cout << "In function " << __FUNCTION__ << endl;
// give thread time to start waiting
Sleep(1000);
Monitor<Mutex>::Lock lock(monitor); // lock monitor
monitor.notify();
} // automaitcally call monitor.unlock()
thread->getThreadControl().join();
return 0;
}
更多的示例請參考test/IceUtil。