Variable of same instance has different values depending on where it's accessed from?

I am working on a MIDI effect plugin in I have a variable which appears to have a different value depending on the class it’s accessed from. To hopefully make things more clear, here’s a rough outline of the relevant code structure.

class AudioProcessor
{
    ScaleTuning scaleTuning;

    void processBlock(); // calls scaleTuning.processMidi()
}

class AudioProcessorEditor
{
    ScaleTuningEditor scaleTuningEditor;
    AudioProcessor audioProcessor; // reference to instance of AudioProcessor
}

class ScaleTuning {
    int key;
    void processMidi();
    int getKey(); // returns key
}

class ScaleTuningEditor
{
    ScaleTuning scaleTuning; // reference to audioProcessor's scaleTuning
    void update(); // called every 30ms by audioProcessorEditor instance
}

If I use getKey from a method called by processBlock (audio thread) it returns the expected value. However, if I call getKey from update (gui thread), it returns a the same value regardless of what key appears to be when called from processBlock.

There is one exception: getKey() returns the right value in update if it’s the first time it’s called after the plugin GUI is opened.

Any idea what’s going on? Is there anything I can do to make this question more clear? I’m fairly new to C++, so I may be making a straightforward noob mistake.

Thank you!

Try

class ScaleTuningEditor
{
    ScaleTuning& scaleTuning; // reference to audioProcessor's scaleTuning
    void update(); // called every 30ms by audioProcessorEditor instance
}

Rail

If you access key from different threads, you should make it atomic. Otherwise the compiler is free to potentially optimize that stuff away.

Yep, it was this! Thank you for catching this, and apologies for the basic mistake!