soundStream, multitheading and secured memory access

Hi !

I’ve got an audio stream that fills a buffer witch is also accessed by my update function in order to draw lines. It sometimes crash for an unknown reason. As AudioIn() works on a parallel thread, I was wondering if my values were getting acced from different theads at the same time.
I thought about using a boolean value to make a lock, but as the AudionIn function could be call at any time, there still is a risk.

Is there a way to prevent values from being accessed by 2 different theard at the same time ?

Thanks

Nicolas

You can lock data acces with std::mutex. http://en.cppreference.com/w/cpp/thread/mutex You can also check the threading examples.

But are you sure that audioIn() works on a parallel thread?

Thanks @underdoeg

In the documentaion of openframeworks I could read “Warning: Be aware that audioIn() and audioOut() will be called on a different thread from your app’s update() / draw() thread.”
It seems logic that my programm will manage more often a group of 255 new samples than a new video frame.
I’ll have a look at what you advised. But there sould be a particular methodology in the case of audio programming.

yes you are right. it is not thread safe.

The mutex is pretty much the only or at least easiest way to handle data in a threaded environment. Audio is no exception there:

float audioData[];
float audioDataThread[];

// in the main thread update
mutex.lock()
audioData = audioDataThread;
mutex.unlock();

// in the audio thread
mutex.lock();
audioDataThread = audioIn;
mutex.unlock();

Or you can check out the ofThreadChannel: http://openframeworks.cc/documentation/utils/ofThreadChannel/

So I guss that from what you’ve written I juste have to manage what will happend if memory is currently used by the other thread.
Dealing with multi threading is not something that is very frequently done, especially for hobbyist programmers.
Thanks again.

yes. basically all you have to do is make sure that every access to data that is shared between threads is surrounded by mutex lock / unlock statements.

Hey @NzNico you will always need mutexes and or buffering when accessing data from different threads.
Sometimes it is better to copy the data to a buffer, using the mutex, and then access from the other thread the buffer instead of the original data. This way will avoid locking the thread when you need to perform heavy processing over the data.
check out this addon I made.


here check the waveformDraw class to see how to deal with mutexes.
cheers

1 Like

@roymacdonald Great ! you made an extention for this problem in particular.
I’ll try this when I have time and I give you feedbacks :slight_smile:
Cheers