Vuo  2.3.2
VuoPool.hh
Go to the documentation of this file.
1 
10 #pragma once
11 
12 #include <string>
13 #include <map>
14 #include <dispatch/dispatch.h>
15 
23 template<typename KeyType, typename InstanceType>
25 {
26 public:
28  typedef InstanceType (*AllocateFunctionType)(KeyType);
29 
30  VuoKeyedPool(std::string instanceTypeString, AllocateFunctionType allocate);
31  InstanceType getSharedInstance(KeyType key);
32  void removeSharedInstance(KeyType key);
33  void visit(void (^b)(KeyType,InstanceType));
34  unsigned int size(void);
35 
36 private:
37  std::string instanceTypeString;
38  AllocateFunctionType allocate;
39  dispatch_queue_t queue;
40  typedef std::map<KeyType,InstanceType> PoolType;
41  PoolType pool;
42 };
43 
47 #define VUOKEYEDPOOL(keyType,instanceType) extern VuoKeyedPool<keyType, instanceType> * instanceType ## Pool
48 
56 #define VUOKEYEDPOOL_DEFINE(keyType,instanceType,allocate) VuoKeyedPool<keyType, instanceType> * instanceType ## Pool = new VuoKeyedPool<keyType, instanceType>(#instanceType, allocate)
57 
61 template<typename KeyType, typename InstanceType>
62 VuoKeyedPool<KeyType,InstanceType>::VuoKeyedPool(std::string instanceTypeString, AllocateFunctionType allocate)
63 {
64 // VLog("%s",instanceTypeString.c_str());
65  this->instanceTypeString = instanceTypeString;
66  this->allocate = allocate;
67  this->queue = dispatch_queue_create(instanceTypeString.c_str(), NULL);
68 }
69 
75 template<typename KeyType, typename InstanceType>
77 {
78 // VLog("%s key=%d",instanceTypeString.c_str(),key);
79  __block InstanceType instance;
80  dispatch_sync(queue, ^{
81  typename PoolType::iterator it = pool.find(key);
82  if (it != pool.end())
83  instance = it->second;
84  else
85  {
86  instance = allocate(key);
87  pool[key] = instance;
88  }
89  });
90  return instance;
91 }
92 
99 template<typename KeyType, typename InstanceType>
101 {
102 // VLog("%s key=%d",instanceTypeString.c_str(),key);
103  dispatch_sync(queue, ^{
104  pool.erase(key);
105  });
106 }
107 
113 template<typename KeyType, typename InstanceType>
114 void VuoKeyedPool<KeyType,InstanceType>::visit(void (^b)(KeyType,InstanceType))
115 {
116  dispatch_sync(queue, ^{
117  for (typename PoolType::iterator i = pool.begin(); i != pool.end(); ++i)
118  b(i->first, i->second);
119  });
120 }
121 
127 template<typename KeyType, typename InstanceType>
129 {
130  __block unsigned int c;
131  dispatch_sync(queue, ^{
132  c = pool.size();
133  });
134  return c;
135 }
136