Skip to content
This repository has been archived by the owner on Jan 4, 2023. It is now read-only.

Added mutex to BluetoothManager #147

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions api/tinyb/BluetoothManager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ friend class BluetoothEventManager;
std::unique_ptr<BluetoothAdapter> default_adapter;
static BluetoothManager *bluetooth_manager;
std::list<std::shared_ptr<BluetoothEvent>> event_list;
std::mutex lock;

BluetoothManager();
BluetoothManager(const BluetoothManager &object);
Expand Down Expand Up @@ -74,16 +75,19 @@ friend class BluetoothEventManager;
* matches an incoming event its' callback will be triggered. Events can be
* the addition of a new Device, GattService, GattCharacteristic, etc. */
void add_event(std::shared_ptr<BluetoothEvent> &event) {
std::lock_guard<std::mutex> guard(lock);
event_list.push_back(event);
}

/** Remove event to checked against events generated by BlueZ.
*/
void remove_event(std::shared_ptr<BluetoothEvent> &event) {
std::lock_guard<std::mutex> guard(lock);
event_list.remove(event);
}

void remove_event(BluetoothEvent &event) {
std::lock_guard<std::mutex> guard(lock);
for(auto it = event_list.begin(); it != event_list.end(); ++it) {
if ((*it).get() == &event) {
event_list.remove(*it);
Expand Down
1 change: 1 addition & 0 deletions src/BluetoothManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ std::weak_ptr<BluetoothEvent> BluetoothManager::find(BluetoothType type,
void BluetoothManager::handle_event(BluetoothType type, std::string *name,
std::string *identifier, BluetoothObject *parent, BluetoothObject &object)
{
std::lock_guard<std::mutex> guard(lock);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi.

Is it possible, that add_event/remove_event API will be called in scope of callback (line 232). If so, crash will occur because 'event_list' will be modified during the iteration. To avoid this copy on write semantics should be implemented.

for (auto it = event_list.begin();
it != event_list.end();) {
if ((*it)->get_type() != BluetoothType::NONE && ((*it)->get_type()) != type) {
Expand Down