CARLA
AtomicList.h
Go to the documentation of this file.
1 // Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
2 // de Barcelona (UAB).
3 //
4 // This work is licensed under the terms of the MIT license.
5 // For a copy, see <https://opensource.org/licenses/MIT>.
6 
7 #pragma once
8 
10 #include "carla/NonCopyable.h"
11 
12 #include <algorithm>
13 #include <mutex>
14 #include <vector>
15 
16 namespace carla {
17 namespace client {
18 namespace detail {
19 
20  /// Holds an atomic pointer to a list.
21  ///
22  /// @warning Only Load method is atomic, modifications to the list are locked
23  /// with a mutex.
24  template <typename T>
25  class AtomicList : private NonCopyable {
26  using ListT = std::vector<T>;
27  public:
28 
29  AtomicList() : _list(std::make_shared<ListT>()) {}
30 
31  template <typename ValueT>
32  void Push(ValueT &&value) {
33  std::lock_guard<std::mutex> lock(_mutex);
34  auto new_list = std::make_shared<ListT>(*Load());
35  new_list->emplace_back(std::forward<ValueT>(value));
36  _list = new_list;
37  }
38 
39  void DeleteByIndex(size_t index) {
40  std::lock_guard<std::mutex> lock(_mutex);
41  auto new_list = std::make_shared<ListT>(*Load());
42  auto begin = new_list->begin();
43  std::advance(begin, index);
44  new_list->erase(begin);
45  _list = new_list;
46  }
47 
48  template <typename ValueT>
49  void DeleteByValue(const ValueT &value) {
50  std::lock_guard<std::mutex> lock(_mutex);
51  auto new_list = std::make_shared<ListT>(*Load());
52  new_list->erase(std::remove(new_list->begin(), new_list->end(), value), new_list->end());
53  _list = new_list;
54  }
55 
56  void Clear() {
57  std::lock_guard<std::mutex> lock(_mutex);
58  _list = std::make_shared<ListT>();
59  }
60 
61  /// Returns a pointer to the list.
62  std::shared_ptr<const ListT> Load() const {
63  return _list.load();
64  }
65 
66  private:
67 
68  std::mutex _mutex;
69 
71  };
72 
73 } // namespace detail
74 } // namespace client
75 } // namespace carla
std::shared_ptr< T > load() const noexcept
Holds an atomic pointer to a list.
Definition: AtomicList.h:25
std::vector< carla::client::detail::CallbackList::Item > ListT
Definition: AtomicList.h:26
This file contains definitions of common data structures used in traffic manager. ...
Definition: Carla.cpp:99
void DeleteByIndex(size_t index)
Definition: AtomicList.h:39
std::shared_ptr< const ListT > Load() const
Returns a pointer to the list.
Definition: AtomicList.h:62
void DeleteByValue(const ValueT &value)
Definition: AtomicList.h:49
Inherit (privately) to suppress copy/move construction and assignment.
void Push(ValueT &&value)
Definition: AtomicList.h:32
AtomicSharedPtr< const ListT > _list
Definition: AtomicList.h:70