2
2
sidebar_position : 4
3
3
---
4
4
5
- # Access Blackboard objects by Reference
5
+ # Zero-copy access to the blackboard, using pointers
6
6
7
7
If you followed the tutorials, you should already know that the Blackboard uses ** value semantic** , i.e.
8
8
the methods ` getInput ` and ` setOutput ` copy the value from/to the blackboard.
@@ -18,7 +18,7 @@ For instance, a Node where it is recommended to use reference semantic is the
18
18
` LoopNode ` decorator, that modifies "in-place" a vector of objects.
19
19
20
20
21
- ## Blackboard entries as Share pointers
21
+ ## Method 1: Blackboard entries as Share pointers
22
22
23
23
For the sake of simplicity, we will consider an object that is expensive to copy,
24
24
called ** Pointcloud** .
@@ -59,16 +59,15 @@ The methods `getInput` and `setOutput` can be used as usual and still have value
59
59
But since the object being copied is a ` shared_ptr ` we are actually accessing the
60
60
pointcloud instance by reference.
61
61
62
- ## Thread safety
62
+ ## Method 2: thread-safe castPtr (recommended since version 4.5.1)
63
63
64
- The most notable issue, when using this approach, is that it is ** NOT thread safe** .
64
+ The most notable issue, when using the ` shared_ptr ` approach, is that it is ** NOT thread safe** .
65
65
66
66
IF multithreading is used, inside a Node (remember that BT.CPP is single-threaded by default),
67
67
then there is no guarantee that a copy of the object being shared isn't accessed during writing.
68
68
69
69
To prevent this issue, we provide a different API that includes a locking mechanism.
70
70
71
-
72
71
This is ** NOT** thread-safe:
73
72
74
73
``` cpp
@@ -80,11 +79,19 @@ getInput("cloud", cloud_ptr);
80
79
The thread-safe alternative:
81
80
82
81
```cpp
83
- // inside this scope, the mutex protecting the instance of "pointcloud" remains locked
82
+ // inside this scope (as long as any_locked exists), a mutex protecting
83
+ // the instance of "cloud" remains locked
84
84
if(auto any_locked = getLockedPortContent("cloud"))
85
85
{
86
- auto cloud_ptr = any_locked.get()->cast<std::shared_ptr<Pointcloud>>();
87
- // modify the pointcloud referenced by cloud_ptr here
86
+ if(any_locked->empty())
87
+ {
88
+ // the entry in the blackboard hasn't been initialized yet.
89
+ }
90
+ else if(auto cloud_ptr = any_locked->cast<std::shared_ptr<Pointcloud>>())
91
+ {
92
+ // Succesful cast to the original value.
93
+ // Modify the pointcloud, referenced by cloud_ptr, here
94
+ }
88
95
}
89
96
```
90
97
0 commit comments