2

I am just trying to implement this answer about mutexes with over 100 upvotes. All I did was copy paste the code, so that my class reads (simplified) like this:

mymutexclass.h

class MyMutexClass {
public:
    void write( uint32_t id, const std::string &str );
    std::string read( uint32_t id ) const;

private:
    boost::shared_mutex _access;
    std::map<uint32_t, std::string> strings;
};

mymutexclass.cpp

void MyMutexClass::write( uint32_t id, const std::string &str ) {
    boost::unique_lock< boost::shared_mutex > lock(_access);
    strings[id] = name;
}
std::string MyMutexClass::read( const uint32_t id ) const {
    boost::shared_lock< boost::shared_mutex > lock(_access); // ERROR HERE
    if( strings.count( id )>0) 
        return strings.at(id);
    else
        return "No value.";
}

And I get an error, only for the read mutex line:

error C2664: 'boost::shared_lock<Mutex>::shared_lock(const boost::shared_lock<Mutex> &)' : cannot convert parameter 1 from 'const boost::shared_mutex' to 'const boost::shared_lock<Mutex> &'   D:\... path ...\mymutexclass.cpp

I am completely lost in the error - what's the difference between the types it complains about? I mean these, from the error:

  • from const boost::shared_mutex
  • to const boost::shared_lock<Mutex> &

And what am I doing wrong? That linked answer was upvoted 100 times, so I guess it's really likely to be correct.

Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • 1
    "That linked answer was upvoted 100 times, so I guess it's really likely to be correct." it's almost 6 years old, though. – SingerOfTheFall Oct 29 '15 at 12:03
  • @SingerOfTheFall Yeah, I said *likely*. But anyway, if there's a problem we might need to find it and fix it because it's top for reader/writer mutex solutions on google. – Tomáš Zato Oct 29 '15 at 12:05

1 Answers1

8

Because your method has a const signature, you are not allowed to change the mutex state, hence you are not allowed to lock it. Changing the mutex to mutable should fix the error:

mutable boost::shared_mutex _access;
Daniel Strul
  • 1,458
  • 8
  • 16