Developer documentation
Version 3.0.3-105-gd3941f44
particlepool.h
Go to the documentation of this file.
1/* Copyright (c) 2008-2022 the MRtrix3 contributors.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 *
7 * Covered Software is provided under this License on an "as is"
8 * basis, without warranty of any kind, either expressed, implied, or
9 * statutory, including, without limitation, warranties that the
10 * Covered Software is free of defects, merchantable, fit for a
11 * particular purpose or non-infringing.
12 * See the Mozilla Public License v. 2.0 for more details.
13 *
14 * For more details, see http://www.mrtrix.org/.
15 */
16
17#ifndef __gt_particlepool_h__
18#define __gt_particlepool_h__
19
20#include <deque>
21#include <stack>
22#include <mutex>
23
24#include "math/rng.h"
25
27
28namespace MR {
29 namespace DWI {
30 namespace Tractography {
31 namespace GT {
32
38 { MEMALIGN(ParticlePool)
39 public:
40 ParticlePool() { }
41
42 ParticlePool(const ParticlePool&) = delete;
43 ParticlePool& operator=(const ParticlePool&) = delete;
44 ~ParticlePool() { }
45
49 Particle* create(const Point_t& pos, const Point_t& dir)
50 {
51 std::lock_guard<std::mutex> lock (mutex);
52 if (avail.empty()) {
53 pool.emplace_back(pos, dir);
54 return &pool.back();
55 } else {
56 Particle* p = avail.top();
57 p->init(pos, dir);
58 avail.pop();
59 return p;
60 }
61 }
62
66 void destroy(Particle* p) {
67 std::lock_guard<std::mutex> lock (mutex);
68 p->finalize();
69 avail.push(p);
70 }
71
75 inline size_t size() const {
76 return pool.size() - avail.size();
77 }
78
82 Particle* random() {
83 std::lock_guard<std::mutex> lock (mutex);
84 if (pool.size() > avail.size())
85 {
86 std::uniform_int_distribution<size_t> dist(0, pool.size()-1);
87 for (int k = 0; k != 5; ++k) {
88 Particle* p = &pool[dist(rng)];
89 if (p->isAlive())
90 return p;
91 }
92 }
93 return nullptr;
94 }
95
99 void clear() {
100 std::lock_guard<std::mutex> lock (mutex);
101 pool.clear();
102 std::stack<Particle*, deque<Particle*> > e {};
103 avail.swap(e);
104 }
105
106 protected:
107 std::mutex mutex;
109 std::stack<Particle*, deque<Particle*> > avail;
111 };
112
113 }
114 }
115 }
116}
117
118#endif // __gt_particlepool_h__
ParticlePool manages creation and deletion of particles, minimizing the no. calls to new/delete.
Definition: particlepool.h:38
std::stack< Particle *, deque< Particle * > > avail
Definition: particlepool.h:109
random number generator
Definition: rng.h:45
constexpr double e
Definition: math.h:39
Eigen::Vector3f Point_t
Definition: particle.h:29
Definition: base.h:24