Skip to content

Commit

Permalink
Add RecursiveMutex class and fix deadlock in remove_listener
Browse files Browse the repository at this point in the history
  • Loading branch information
ion098 committed Jun 5, 2024
1 parent 2b4d5ab commit 6e152b8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion include/gamepad/event_handler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <atomic>

#include "gamepad/todo.hpp"
#include "gamepad/recursive_mutex.hpp"
#include "pros/rtos.hpp"

namespace Gamepad {
Expand Down Expand Up @@ -52,6 +53,6 @@ template <typename... Args> class EventHandler {
}
private:
std::map<uint32_t, Listener> listeners;
pros::Mutex mutex;
Gamepad::RecursiveMutex mutex;
};
} // namespace Gamepad
29 changes: 29 additions & 0 deletions include/gamepad/recursive_mutex.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include "pros/apix.h"
#include "pros/rtos.h"
#include <system_error>

namespace Gamepad {

class RecursiveMutex {
public:
RecursiveMutex(): mutex(pros::c::mutex_recursive_create()) {}
bool take(std::uint32_t timeout = TIMEOUT_MAX) {
return pros::c::mutex_recursive_take(mutex, timeout);
}
void lock() {
if (!this->take()) throw std::system_error();
}
bool try_lock() {
return this->take(0);
}
bool give() {
return pros::c::mutex_recursive_give(mutex);
}
void unlock() {
this->give();
}
private:
pros::mutex_t mutex;
};

}

0 comments on commit 6e152b8

Please sign in to comment.