当C++遇到IOS应用开发---LRUCache缓存(2)
if (lock->write) {//当已是写锁时,则去掉读锁记数器
__sync_sub_and_fetch(&lock->read,1);
} else {
break;
}
}
}
static inline void
rwlock_wlock(struct rwlock *lock) {
__sync_lock_test_and_set(&lock->write,1);
while(lock->read) {
//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; 
}HashKey; 
    
typedef struct _HashValue 
{ 
    id value_; 
    virtual_time access_; 
}HashValue; 
 
//仅针对HashKey比较器 
template <class key_t> 
struct hashkey_compare{ 
    bool operator()(key_t x, key_t y) const{ 
        return x < y; 
    } 
}; 
        
	
相关新闻>>
- 发表评论
- 
				
- 最新评论 进入详细评论页>>








![[iPhone中级]iPhone团购信息客户端的开发 (二)](/uploads/allimg/131022/200H11235-0-lp.png)

