Vuo 2.4.4
Loading...
Searching...
No Matches
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
25template<typename KeyType, typename InstanceType>
27{
28public:
30 typedef InstanceType (*AllocateFunctionType)(KeyType);
31
32 VuoKeyedPool(std::string instanceTypeString, AllocateFunctionType allocate);
33 InstanceType useSharedInstance(KeyType key);
34 void disuseSharedInstance(InstanceType instance);
35 void visit(void (^b)(KeyType,InstanceType));
36 unsigned int size(void);
37
38private:
39 std::string instanceTypeString;
40 AllocateFunctionType allocate;
41 dispatch_queue_t queue;
42 typedef std::map<KeyType,InstanceType> PoolType;
43 PoolType pool;
44};
45
49#define VUOKEYEDPOOL(keyType,instanceType) extern VuoKeyedPool<keyType, instanceType> * instanceType ## Pool
50
58#define VUOKEYEDPOOL_DEFINE(keyType,instanceType,allocate) VuoKeyedPool<keyType, instanceType> * instanceType ## Pool = new VuoKeyedPool<keyType, instanceType>(#instanceType, allocate)
59
63template<typename KeyType, typename InstanceType>
64VuoKeyedPool<KeyType,InstanceType>::VuoKeyedPool(std::string instanceTypeString, AllocateFunctionType allocate)
65{
66// VLog("%s",instanceTypeString.c_str());
67 this->instanceTypeString = instanceTypeString;
68 this->allocate = allocate;
69 this->queue = dispatch_queue_create(instanceTypeString.c_str(), NULL);
70}
71
82template<typename KeyType, typename InstanceType>
84{
85// VLog("%s key=%d",instanceTypeString.c_str(),key);
86 __block InstanceType instance;
87 dispatch_sync(queue, ^{
88 typename PoolType::iterator it = pool.find(key);
89 if (it != pool.end())
90 instance = it->second;
91 else
92 {
93 instance = allocate(key);
94 pool[key] = instance;
95 }
96
97 VuoRetain(instance);
98 });
99 return instance;
100}
101
107template<typename KeyType, typename InstanceType>
109{
110 if (!instance)
111 return;
112
113// VLog("%s key=%d",instanceTypeString.c_str(),key);
114 dispatch_sync(queue, ^{
115 for (auto it = pool.begin(); it != pool.end(); ++it)
116 if (it->second == instance)
117 {
118 int referenceCount = VuoRelease(it->second);
119 if (referenceCount == 0)
120 {
121 pool.erase(it);
122 break;
123 }
124 }
125 });
126}
127
133template<typename KeyType, typename InstanceType>
134void VuoKeyedPool<KeyType,InstanceType>::visit(void (^b)(KeyType,InstanceType))
135{
136 dispatch_sync(queue, ^{
137 for (typename PoolType::iterator i = pool.begin(); i != pool.end(); ++i)
138 b(i->first, i->second);
139 });
140}
141
147template<typename KeyType, typename InstanceType>
149{
150 __block unsigned int c;
151 dispatch_sync(queue, ^{
152 c = pool.size();
153 });
154 return c;
155}