Zeroc ICE 源码分析二 IceUtil

ICE提供了一个跨平台的c++ middleware,包含在源码的include/IceUtil中。IceUtil中包含的主要类如下图所示:

Zeroc ICE 源码分析二 IceUtil_第1张图片

这些类主要提供了3类跨平台的基础功能:

1. SmartPoint / SharedPtr 功能。 Shared 中包含了__incRef() 和 __decRef()的方法。并且当 __decRef中的引用计数为0时会delete this.

Handle在Constructor 和 Destructor 中会调用Shared 的 __incRef() 和 __decRef()方法。如下所示:

#include 
#include 
#include 

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 GetMyShared()
{
	Handle mySharedHandle = new MyShared();
	Handle mySharedHandle2 = mySharedHandle;
	return mySharedHandle2;
}

void TestMyShared()
{
	Handle 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 
#include 
#include 

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 
#include 
#include 

using namespace std;
using namespace IceUtil;

Monitor monitor;

class MyThread : public Thread
{
public:
	virtual void run()
	{
		Monitor::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::Lock lock(monitor); // lock monitor
		monitor.notify();
	} // automaitcally call monitor.unlock()

	thread->getThreadControl().join();
	return 0;
}
更多的示例请参考test/IceUtil。

你可能感兴趣的:(Zeroc ICE 源码分析二 IceUtil)