Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Herb Sutters monitor class work?

Tags:

c++

c++11

I am trying to understand the monitor class that Herb Sutter presented on C++ and Beyond 2012:

template<typename T>
class monitor {
private:
    mutable T t;
    mutable std::mutex m;

public:
    monitor(T t_ = T{}) : t{ t_ } {} 
    template<typename F>
    auto operator()(F f) const -> decltype(f(t))
    {
        std::lock_guard<std::mutex> _{ m }; return f(t);
    }
}; 

I have managed to create a class that does the same thing in a more old fashioned and simpler (for me at least) way:

template<typename T>
class MyMonitor {
public:
    MyMonitor() { t = T(); }

    template<typename F>
    auto callFunc(F f) {
        std::lock_guard<std::mutex> lock(m);
        return f(t);
    }

private:
    T          t;
    std::mutex m;
};  

In which ways are Herb Sutters code better than mine?

like image 376
Andy Avatar asked Oct 15 '22 05:10

Andy


1 Answers

In which ways are Herb Sutters code better than mine?

  • Your T should be default constructible, and assignable.
  • In Herb Sutters code, T should be copy constructible.

  • Herb Sutters code allows to initialize the member.

  • Your operator () doesn't handle reference.

like image 55
Jarod42 Avatar answered Oct 18 '22 22:10

Jarod42