jeudi 29 juin 2023

Efficient thread safe observer design pattern without expensive copying

What's the efficient way to implement a thread safe observer design pattern ?

Using the following code:

#include <mutex>
#include <vector>

class Subject {
public:
    void addObserver(Observer* observer) {
        std::lock_guard<std::mutex> lock(mutex_);
        observers_.push_back(observer);
    }

    void removeObserver(Observer* observer) {
        std::lock_guard<std::mutex> lock(mutex_);
        // Remove the observer from the vector
    }

    void notifyObservers() {
        std::lock_guard<std::mutex> lock(mutex_);
        for (Observer* observer : observers_) {
            observer->update();
        }
    }

private:
    std::mutex mutex_;
    std::vector<Observer*> observers_;
};

it's not recommended to hold a lock and call a callback ! Also coping the list of observers each time I send a notification I not efficient also.

Is there an efficient way to achieve thread safety.

Aucun commentaire:

Enregistrer un commentaire