基于 ArnetMiner 的高效搜索缓存机制的研究及实现

 

缓存操作中的互斥机制

考虑到多线程并发访问 cache, 我所提供的函数(名为 operator()) 对外必须保证其原子性. 

ArnetMiner 中控制同步使用了 boost::mutex, 然而我认为, ArnetMiner 大量使用了 windows.h, 因此向 linux 移植的可能性很小. 所以决定使用 windows 的 CreateMutex, WaitForSingleObject/ReleaseMutext 以及 CloseHandle 等函数控制并发.

为了实现方便的互斥操作, 我将其封装:

// Mutex.h
// This is a windows mutex semaphore class.

#include <windows.h>

class Mutex
{
public:
Mutex(DWORD milli);
~Mutex();

public:
// Interface
bool Lock() throw ();
bool UnLock() throw ();

private:
// data
HANDLE m_mutex;
DWORD m_elapse; // Milli Second.
};

其中 Lock() 和 UnLock() 设计为不抛出任何异常.

在 Lock() 内部, 使用了 WaitForSingleObject 来实现对互斥量的控制.

这个类被用于 Cache 中, 作为互斥操作的对象:

bool Cache::operator()(string &out, const string &in) throw ()
{
bool hit = false;

if (m_mutex.Lock())
{
if (m_toggle) // If you want to use cache.
{
try
{
if (!(hit = get(out, in))) // If cache did not hit.
{
refresh(Node(in, out)); // Replace old one.
}
}
catch (...)
{}
}

m_mutex.UnLock();
}

return hit;
}


 

posted @ 2012-03-07 14:07  walfud  阅读(375)  评论(0编辑  收藏  举报