lock in AlsaBridge v_0
authorFrantišek Kučera <franta-hg@frantovo.cz>
Mon, 21 Dec 2020 16:44:39 +0100
branchv_0
changeset 9ee976a1d1f0a
parent 8 87dfa7c89294
child 10 4d95b089457d
lock in AlsaBridge
AlsaBridge.cpp
     1.1 --- a/AlsaBridge.cpp	Sun Dec 20 01:56:47 2020 +0100
     1.2 +++ b/AlsaBridge.cpp	Mon Dec 21 16:44:39 2020 +0100
     1.3 @@ -17,6 +17,7 @@
     1.4  #include <iostream>
     1.5  #include <stdexcept>
     1.6  #include <thread>
     1.7 +#include <mutex>
     1.8  #include <atomic>
     1.9  
    1.10  #include <alsa/asoundlib.h>
    1.11 @@ -32,18 +33,21 @@
    1.12  	snd_rawmidi_t* input;
    1.13  	snd_rawmidi_t* output;
    1.14  	std::thread receivingThread;
    1.15 +	std::recursive_mutex midiMutex;
    1.16  	std::atomic<bool> stopped{false};
    1.17  
    1.18  	void run() {
    1.19  		while (!stopped) {
    1.20 -			// TODO: poll
    1.21 -			uint8_t buffer[256];
    1.22 -			ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
    1.23 -			if (length > 0 && length <= sizeof (buffer)) {
    1.24 -				// TODO: multiple messages combined together?
    1.25 -				djmFix->receive(MidiMessage(buffer, buffer + length));
    1.26 +			{
    1.27 +				std::lock_guard<std::recursive_mutex> lock(midiMutex);
    1.28 +				// TODO: poll
    1.29 +				uint8_t buffer[256];
    1.30 +				ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
    1.31 +				if (length > 0 && length <= sizeof (buffer)) {
    1.32 +					// TODO: multiple messages combined together?
    1.33 +					djmFix->receive(MidiMessage(buffer, buffer + length));
    1.34 +				}
    1.35  			}
    1.36 -
    1.37  			std::this_thread::sleep_for(std::chrono::milliseconds(100));
    1.38  		}
    1.39  	}
    1.40 @@ -78,6 +82,7 @@
    1.41  	}
    1.42  
    1.43  	virtual void send(MidiMessage midiMessage) override {
    1.44 +		std::lock_guard<std::recursive_mutex> lock(midiMutex);
    1.45  		ssize_t length = snd_rawmidi_write(output, midiMessage.data(), midiMessage.size());
    1.46  		std::cerr << "AlsaBridgeImpl::send(): length = " << length << std::endl; // TODO: do not mess STDIO
    1.47  	}