--- a/AlsaBridge.cpp Sun Dec 20 01:56:47 2020 +0100
+++ b/AlsaBridge.cpp Mon Dec 21 16:44:39 2020 +0100
@@ -17,6 +17,7 @@
#include <iostream>
#include <stdexcept>
#include <thread>
+#include <mutex>
#include <atomic>
#include <alsa/asoundlib.h>
@@ -32,18 +33,21 @@
snd_rawmidi_t* input;
snd_rawmidi_t* output;
std::thread receivingThread;
+ std::recursive_mutex midiMutex;
std::atomic<bool> stopped{false};
void run() {
while (!stopped) {
- // TODO: poll
- uint8_t buffer[256];
- ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
- if (length > 0 && length <= sizeof (buffer)) {
- // TODO: multiple messages combined together?
- djmFix->receive(MidiMessage(buffer, buffer + length));
+ {
+ std::lock_guard<std::recursive_mutex> lock(midiMutex);
+ // TODO: poll
+ uint8_t buffer[256];
+ ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
+ if (length > 0 && length <= sizeof (buffer)) {
+ // TODO: multiple messages combined together?
+ djmFix->receive(MidiMessage(buffer, buffer + length));
+ }
}
-
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
@@ -78,6 +82,7 @@
}
virtual void send(MidiMessage midiMessage) override {
+ std::lock_guard<std::recursive_mutex> lock(midiMutex);
ssize_t length = snd_rawmidi_write(output, midiMessage.data(), midiMessage.size());
std::cerr << "AlsaBridgeImpl::send(): length = " << length << std::endl; // TODO: do not mess STDIO
}