]> git.sesse.net Git - nageru/blobdiff - shared/midi_device.h
Fix a deadlock in Futatabi when using MIDI devices.
[nageru] / shared / midi_device.h
index 9c76d18b9d1a667c18cf2111f9fc36d4ac63ee80..5b1c3ade4c4ea8c884f9b131f5caa735b082268c 100644 (file)
@@ -28,13 +28,26 @@ public:
 
 class MIDIDevice {
 public:
+       struct LightKey {
+               enum { NOTE, CONTROLLER } type;
+               unsigned number;
+
+               bool operator< (const LightKey& other) const
+               {
+                       if (type != other.type) {
+                               return type < other.type;
+                       }
+                       return number < other.number;
+               }
+       };
+
        MIDIDevice(MIDIReceiver *receiver);
        ~MIDIDevice();
        void start_thread();
 
-       void update_lights(const std::map<unsigned, uint8_t> &active_lights)
+       void update_lights(const std::map<LightKey, uint8_t> &active_lights)
        {
-               std::lock_guard<std::mutex> lock(mu);
+               std::lock_guard<std::recursive_mutex> lock(mu);
                update_lights_lock_held(active_lights);
        }
 
@@ -42,16 +55,18 @@ private:
        void thread_func();
        void handle_event(snd_seq_t *seq, snd_seq_event_t *event);
        void subscribe_to_port_lock_held(snd_seq_t *seq, const snd_seq_addr_t &addr);
-       void update_lights_lock_held(const std::map<unsigned, uint8_t> &active_lights);
+       void update_lights_lock_held(const std::map<LightKey, uint8_t> &active_lights);
 
        std::atomic<bool> should_quit{false};
        int should_quit_fd;
 
-       mutable std::mutex mu;
-       MIDIReceiver *receiver;  // Under <mu>.
+       // Recursive because the MIDI receiver may update_lights() back while we are sending it stuff.
+       // TODO: Do we need this anymore after receiver is not under the lock?
+       mutable std::recursive_mutex mu;
+       MIDIReceiver *receiver;  // _Not_ under <mu>; everything on it should be thread-safe.
 
        std::thread midi_thread;
-       std::map<unsigned, uint8_t> current_light_status;  // Keyed by note number. Under <mu>.
+       std::map<LightKey, uint8_t> current_light_status;  // Keyed by note number. Under <mu>.
        snd_seq_t *alsa_seq{nullptr};  // Under <mu>.
        int alsa_queue_id{-1};  // Under <mu>.
        std::atomic<int> num_subscribed_ports{0};