How to lock threads in real-time applications : <p>Absolute multi-threading newbie here. </p>

<p>I have a multimedia application that plays music. Specifically, it has an audio thread that reads some data - e.g. a waveform - and sends it to the sound card. This is a real-time operation, so it must be executed as quick as possible in a "non-blocking" way. </p>

<p>On the other side there is another thread that takes care of the user interface. Here the user can perform some operations on that data - e.g. modify the waveform by adding or removing chunks. This of course should be possible, but the audio thread must keep running undisturbed with that data always available.</p>

<p>My first idea was something like this (c++-ish pthread pseudo code):</p>



<p>Audio thread:</p>

<pre class="lang-cpp prettyprint-override"><code>vector&lt;sample&gt; samples; // this is shared between this thread and the UI thread
mutexLock();
for (Sample sample : samples)
    play(sample);
mutexUnlock();
</code></pre>

<p>And the UI thread:</p>

<pre class="lang-cpp prettyprint-override"><code>void onEditSample()
{
    while (mutexTryLock() == 0)
    {
        editSamples(samples);
        mutexUnlock();
        break;
    }
}
</code></pre>

<p>But I'm not really sure about the try-lock part. What is in your opinion the best way to deal with this?</p>
