getDefaultMidiPort in thread and thread::wait() precision


I'm developing a standalone program that sends MIDI messages from a thread (has to be very precise, midi clock, this is the only thing this thread has to do.). I used thread a thread safe circular buffer (based on abstractFifo) for getting information to this thread, but now I have a few questions.

- As I read on this forum you should make 1 audioDeviceManager top level and you don't have to make new audioDeviceManagers for each thread/class... Is it thread safe to pass a reference to the audioDeviceManager and call in my run():

if(deviceManager.getDefaultMidiOutput() != nullptr) /* SEND MIDI STUFF WITH THIS OUTPUT */

Or should i lock this when the setup changes with a changeListener? What would be the correct way to do this?


- How precise is the Thread::wait() on a high priority thread, I guess this depends on the machine but are there better ways to do this? The wait() has 1ms precision, but I store what the delta time is between the rounded int value and the more precise float value. I tried to wait untill a few milliseconds before the time where the event should happen and check Time::getCurrentMillisHighPrecision() but that took a lot of CPU (what I expected). 


Thanks and sorry if I ask stupid questions!


Thread::wait is OK, but you might want to use Time::waitForMillisecondCounter(), which might be a little bit better.

Thanks Jules!

What's your opinion on the audioDeviceManager? Is it safe to call in the thread? Or would adding another (just for MIDI) audiodevicemanager and locking it when changing be a better option? 

AudioDeviceManager isn't thread-safe, so no, that wouldn't be safe.

So I should lock the thread when doing the MIDI adjustments? And unlock after it's done?

This should be thread safe isn't it? It doesn't matter if the thread is locked for a period of time, after a midi device change I should restart the midi clock anyway.

Thanks for the quick answer and sorry if these are beginner questions ;)

It depends on your use-case, really. You might want to make the thread own its own MidiOutput object rather than let the AudioDeviceManager potentially delete it while in use.

Ok, sound logic that the thread owns the MidiOutput so the audiodevicemanager can't mess with it. I'll try that!

Thanks again!


EDIT: it seems like you can't notify() Time::waitForMillisecondCounter() when I need to change the clock speed. I need to figur out some way to let the thread wait (with waitformillisecondcounter() ) AND able to be notified, whatever happens first. First thought was to check for an atomic bool after I wake the thread up with notify(). But it doesn't seem the right answer (I propably need to do some extra reading in "C++ concurrency in action")