blob: 5b1c3e09ab947ef4c6290cc449fee68730c50cae [file] [log] [blame]
Zhenkai Zhu406f37a2012-03-05 20:23:20 -08001/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2012 University of California, Los Angeles
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
19 * 卞超轶 Chaoyi Bian <bcy@pku.edu.cn>
20 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
21 */
Chaoyi Bian44fff0c2012-03-07 21:07:22 -080022
23#include "sync-interest-table.h"
24
25using namespace std;
26using namespace boost;
27
28namespace Sync
29{
30
31unordered_set<string> SyncInterestTable::fetchAll()
32{
Zhenkai Zhu075bd9d2012-03-08 16:06:45 -080033 expireInterests();
Zhenkai Zhu77169cb2012-03-08 16:02:52 -080034
35 recursive_mutex::scoped_lock lock(m_mutex);
36 unordered_set<string> entries;
37 for (unordered_map<string, time_t>::iterator it = m_table.begin(); it !=
38 m_table.end(); ++it) {
39 entries.insert(it->first);
40 }
41
42 return entries;
Chaoyi Bian44fff0c2012-03-07 21:07:22 -080043}
44
45bool SyncInterestTable::insert(string interest)
46{
Zhenkai Zhu77169cb2012-03-08 16:02:52 -080047 recursive_mutex::scoped_lock lock(m_mutex);
Zhenkai Zhubc7bfce2012-03-09 14:37:52 -080048 unordered_map<string, time_t>::iterator it = m_table.find(interest);
49 if (it != m_table.end())
50 m_table.erase(it);
Zhenkai Zhu77169cb2012-03-08 16:02:52 -080051 time_t currentTime = time(0);
52 m_table.insert(make_pair(interest, currentTime));
Chaoyi Bian44fff0c2012-03-07 21:07:22 -080053}
54
Zhenkai Zhu075bd9d2012-03-08 16:06:45 -080055SyncInterestTable::SyncInterestTable() {
Zhenkai Zhu77169cb2012-03-08 16:02:52 -080056 m_thread = thread(&SyncInterestTable::periodicCheck, this);
57}
58
59void SyncInterestTable::expireInterests() {
60 recursive_mutex::scoped_lock lock(m_mutex);
61 time_t currentTime = time(0);
62 unordered_map<string, time_t>::iterator it = m_table.begin();
63 while(it != m_table.end()) {
64 time_t timestamp = it->second;
65 if (currentTime - timestamp > m_checkPeriod) {
66 it = m_table.erase(it);
67 }
68 else
69 ++it;
70 }
71}
72
73void SyncInterestTable::periodicCheck() {
74 sleep(4);
Zhenkai Zhu075bd9d2012-03-08 16:06:45 -080075 expireInterests();
Zhenkai Zhu77169cb2012-03-08 16:02:52 -080076}
77
78}