summaryrefslogtreecommitdiff
path: root/src/common/sharedptr_registry.hpp
blob: bd0c656024d2f27afc1d3bec44f95d2443f54e64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#ifndef CEPH_SHAREDPTR_REGISTRY_H
#define CEPH_SHAREDPTR_REGISTRY_H

#include <map>
#include <memory>
#include "common/Mutex.h"
#include "common/Cond.h"

/**
 * Provides a registry of shared_ptr<V> indexed by K while
 * the references are alive.
 */
template <class K, class V>
class SharedPtrRegistry {
  Mutex lock;
  Cond cond;
  typedef std::tr1::shared_ptr<V> VPtr;
  typedef std::tr1::weak_ptr<V> WeakVPtr;
  map<K, WeakVPtr> contents;

  class OnRemoval {
    SharedPtrRegistry<K,V> *parent;
    K key;
  public:
    OnRemoval(SharedPtrRegistry<K,V> *parent, K key) :
      parent(parent), key(key) {}
    void operator()(V *to_remove) {
      {
	Mutex::Locker l(parent->lock);
	parent->contents.erase(key);
	parent->cond.Signal();
      }
      delete to_remove;
    }
  };
  friend class OnRemoval;

public:
  SharedPtrRegistry() : lock("SharedPtrRegistry::lock") {}

  VPtr lookup(const K &key) {
    Mutex::Locker l(lock);
    while (1) {
      if (contents.count(key)) {
	VPtr retval = contents[key].lock();
	if (retval)
	  return retval;
      } else {
	break;
      }
      cond.Wait(lock);
    Mutex::Locker l(lock);
    }
    return VPtr();
  }

  VPtr lookup_or_create(const K &key) {
    Mutex::Locker l(lock);
    while (1) {
      if (contents.count(key)) {
	VPtr retval = contents[key].lock();
	if (retval)
	  return retval;
      } else {
	break;
      }
      cond.Wait(lock);
    }
    VPtr retval(new V(), OnRemoval(this, key));
    contents[key] = retval;
    return retval;
  }

  template<class A>
  VPtr lookup_or_create(const K &key, const A &arg) {
    Mutex::Locker l(lock);
    while (1) {
      if (contents.count(key)) {
	VPtr retval = contents[key].lock();
	if (retval)
	  return retval;
      } else {
	break;
      }
      cond.Wait(lock);
    }
    VPtr retval(new V(arg), OnRemoval(this, key));
    contents[key] = retval;
    return retval;
  }
};

#endif