How best to read member data from another class within a separate thread?

Hey everybody, me again, I know this is the 3rd post in 3 days but this time I promise I spent like 3 full minutes squinting at StackOverflow.

So anyway

I suppose what I’m trying to do is create my own slider listener. I created a thread within my own class - DrawGraphics, that is reading the value of a slider, a UI component in MainComponent, at varying intervals.

The below code is on a separate thread within DrawGraphics which is created when the slider is dragged and join()'d later when the slider is released.

DrawGraphics.cpp

void DrawGraphics::clock(unsigned int rate) // accepts an integer as Hz
{
	
	const MessageManagerLock mml(Thread::getCurrentThread());

	if (mml.lockWasGained())
	{
		DBG("mml lock succesful");
	}
	else
	{
		DBG("mml locked unsuccesful");
		return;
	}
	
	mainComponent = new MainComponent; // access class by prior forward declaration

        ... CLOCK STUFF

	while (mPlayState == PlayState::Playing)
	{
		double sliderOutput = mainComponent->ampSlider.getValue(); // read the slider
		DBG("Slider output is : " << sliderOutput);

                ... MORE CLOCK STUFF
	}

}

MessageManagerLock is needed to access MainComponent but as a result, stops the UI entirely. If I remove it as an object, the thread can run concurrently to the UI with no problems.

So I’d like to be able to access MainComponent member data from within the child thread (specifically, polling the slider value) and have the UI continue running on the parent thread.

How can I have my cake and eat it too?

PS. If anyone knows of any tutorials that cover JUCE thread management and could point me in the right direction it would be much obliged

The Slider value updates inside of the MessageManager thread, so reading it outside of that context gains you no benefit. The simplest you can do is store the current slider value in an atomic member variable, which you can read from your other thread.

class YourClass
{
public:
    YourClass()
    {
		yourSlider.onChange = [this]() { curSliderValue.store(yourSlider.getValue()); }
    }
	
	int getCurSliderValue { return curSliderValue.load(); }
private:
	Slider yourSlider;
	std::atomic<int> curSliderValue { 0 };
}
1 Like

YES! that worked perfectly. Thanks so much :slight_smile: