bloom filter

  hash表可以根据关键字直接定位记录在表中的存储位置,关键字通过一个映射函数计算得到这个地址,这个映射函数叫hash函数。bloom filter是一种多hash函数映射的快速查找算法,用于判断一个元素是否已经存在于集合中。

  一个最典型的应用是:网络爬虫。每个网页都可能包含大量的url,这些url指向爬虫下一步爬的目的地,但是很有可能在之前已经搜索过了,所以在保存这些url之前,需要首先判断,它们是否已经访问过,否则就会形成闭环。

#define HASH_FUNC_NUM 8
#define BLOOM_SIZE 1000000
#define BITSIZE_PER_BLOOM 32
#define LIMIT (BLOOM_SIZE * BITSIZE_PER_BLOOM)

pthread_mutex_t bt_lock = PTHREAD_MUTEX_INITIALIZER
static int bloom_table[BLOOM_SIZE] = {0};

int search(char *url)
{
      pthread_mutex_lock(&bt_lock);
      for(unsigned int i=0; i<HASH_FUNC_NUM;i++)
      {
                  unsigned int h = encrypt(url, i);
                  h %= LIMIT;
                  unsigned int index = h/BITSIZE_PER_BLOOM;
                  unsigned int pos = h%BITSIZE_PER_BLOOM;
                  if(bloom_table[index] & (0x80000000 >> pos))
                              res++;
                  else
                              bloom_table[index] != (0x80000000>>pos);
       }  
 
       pthread_mutex_unlock(&bt_lock);
       return (res == HASH_FUNC_NUM);
}

 

posted on 2017-05-16 00:37  残余的光  阅读(129)  评论(0编辑  收藏  举报

导航