Skip to content

Instantly share code, notes, and snippets.

@ffAudio
Created July 19, 2022 14:33
Show Gist options
  • Save ffAudio/8be1c82b17f48a7c59d48001516b6d7b to your computer and use it in GitHub Desktop.
Save ffAudio/8be1c82b17f48a7c59d48001516b6d7b to your computer and use it in GitHub Desktop.
Wrap an atomic value that always reflects a juce::Value for use in the audio thread
#pragma once
#include <atomic>
#include <juce_data_structures/juce_data_structures.h>
template<typename ValueType>
class AtomicValue
{
public:
AtomicValue()
{
variantValue.addListener (&setter);
}
AtomicValue (juce::Value& value) : variantValue (value)
{
variantValue.addListener (&setter);
}
void attachTo (const juce::Value& value)
{
variantValue.referTo (value);
atomicValue.store (ValueType (variantValue.getValue()));
}
ValueType get() { return atomicValue.load(); }
void set (ValueType newValue)
{
variantValue.getValue() = newValue;
}
struct Setter : public juce::Value::Listener
{
Setter (std::atomic<ValueType>& atomic) : atomicValue (atomic) {}
void valueChanged (juce::Value& value) override { atomicValue.store (ValueType (value.getValue())); }
std::atomic<ValueType>& atomicValue;
};
private:
std::atomic<ValueType> atomicValue;
Setter setter { atomicValue };
juce::Value variantValue;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AtomicValue)
};
/*
// Use:
AtomicValue<double> something;
juce::ValueTree tree {"Foo"};
something.attachTo (tree.getPropertyAsValue("something", nullptr));
// optional attach controls to the same value
slider.getValueObject().referTo (tree.getPropertyAsValue("something", nullptr));
// In Audio processing:
auto s = something.get(); // returns a double
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment