background image

//http://blog.itmem.com/?m=201204
//http://gcc.gnu.org/onlinedocs/gcc-4.6.2/gcc/Atomic-Builtins.html
__sync_synchronize();//很重要,如果去掉,g++ -O3 优化编译后的生成的程序会产生死锁
}
}

static inline void
rwlock_wunlock(struct rwlock *lock) {
__sync_lock_release(&lock->write);
}

static inline void
rwlock_runlock(struct rwlock *lock) {
__sync_sub_and_fetch(&lock->read,1);

    这里并未使用 pthread_mutex_t 来设计锁,而是使用了__sync_fetch_and_add 指令体系,
当然最终是否如上面链接中作者所说的比

pthread_mutex_t 性能要高 7-8 倍,我没测试过,

感兴趣的朋友也可以帮助测试一下。

    有了这两个类之后,我又补充了原文作者中所提到了 KEY 比较方法的定义,同时引入了
id 来支持 object-c 的对象缓存,最终代码修改如下:

[cpp]
#ifndef _MAP_LRU_CACHE_H_
#define _MAP_LRU_CACHE_H_

#include <string.h>
#include <iostream>
#include “rwlock.h”
#include <stdio.h>
#include <sys/malloc.h>
using namespace std;

namespace lru_cache {

static const int DEF_CAPACITY = 100000;//默认缓存记录数

typedef unsigned long long virtual_time;

typedef struct _HashKey
{
NSString* key;