Sharing state with an audio thread #300
-
Hi ! I'm wondering whether
But I have some concerns and questions. Let's consider this: immer::atom<state_t> global_state; // 'owned' and mutated by the main thread
void audio_callback(/* args */){
const immer::box<state_t> state = global_state.load();
/* do stuff */
} // <-- `state` goes out of scope here It is my understanding that if by any chance the global state changed, and the audio thread ends up having the last reference to the underlying Option 1: defer destructionOne naive fix I can see would be to defer the destruction of the box, with some kind of lockfree hand-written garbage collection, e.g.: immer::atom<state_t> global_state; // 'owned' and mutated by the main thread
lockfree_queue<state_t>> gc_queue;
void audio_callback(/* args */){
immer::box<state_t> state = global_state.load();
/* do stuff */
gc_queue.emplace(std::move(state));
}
void gc_callback()
{
while(!gc_queue.empty()) gc_queue.pop();
} Option 2: restrictions on the typeAnother (less flexible way) would be to have the audio callback get the state by value, but that means we have to be sure no alloc/dealloc occur. // guarantees no alloc/dealloc
static_assert(std::is_trivially_copy_constructible_v<state_t>);
static_assert(std::is_trivially_destructible_v<state_t>);
immer::atom<state_t> global_state; // 'owned' and mutated by the main thread
void audio_callback(/* args */){
const state_t state = static_cast<state_t>(global_state);
} It could work, but then I guess structural sharing within Am I missing something? Are there memory policies that already do that sort of stuff ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Good question and very detailed eye ;) Option 1 is what I use in my code. You can wrap the pattern with some utilities to make it safe and easy for the user. It works well in practice and I never needed anything else. Memory policies sadly can't be used for this purpose the way they're currently designed. I could envision API changes that would allow it (basically allowing the implementation of option 1 under the hood), but as I just mentioned, the workaround was good enough for me. |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot for your answer! On the topic of implementing the memento pattern, do you have any recommendations? Are there any idioms of the library that could help? |
Beta Was this translation helpful? Give feedback.
Good question and very detailed eye ;)
Option 1 is what I use in my code. You can wrap the pattern with some utilities to make it safe and easy for the user. It works well in practice and I never needed anything else.
Memory policies sadly can't be used for this purpose the way they're currently designed. I could envision API changes that would allow it (basically allowing the implementation of option 1 under the hood), but as I just mentioned, the workaround was good enough for me.