Peter Lee
Peter Lee

Reputation: 13809

Boost lock_guard<boost::mutex> Throws EINVAL Exception

I have some static user data like:

private:
    static std::map<unsigned long, UserDataSharedPtr> userStore_;
    static boost::mutex                               mutexUserData;

public:
    static void RemoveUserData(unsigned long id)
    {
        boost::lock_guard<boost::mutex> lock(mutexUserData);
        std::map<unsigned long, UserDataSharedPtr>::iterator it = userStore_.find(id);
        if (it != userStore_.end())
        {
            userStore_.erase(it);
        }
    }
    static void AddUserData(unsigned long id, UserDataSharedPtr ud)
    {
        boost::lock_guard<boost::mutex> lock(mutexUserData);
        userStore_.insert(std::make_pair(id, ud));
    }

And in a load testing, my program crashes at the line:

boost::lock_guard<boost::mutex> lock(mutexUserData);

With exception:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::lock_error> >'
  what():  boost::lock_error

The Call Stack:

boost::mutex::lock() at mutex.hpp:55 0x81aeb22  
boost::lock_guard<boost::mutex>::lock_guard() at locks.hpp:257 0x81b2cb3    
..........RemoveUserData() at ..............:69 0x81b0b28   

And the boost::mutex::lock() at mutex.hpp

pthread_mutex_t m;
void lock()
{
    int const res=pthread_mutex_lock(&m);
    if(res)
    {
        boost::throw_exception(lock_error(res));
    }
}

Here pthread_mutex_lock(&m) returns 22, and I check 22 is EINVAL: The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread's priority is higher than the mutex's current priority ceiling

What should I do?

I googled a lot, but I got no luck.

Thanks.

Peter

Upvotes: 2

Views: 2298

Answers (2)

Vlad Didenko
Vlad Didenko

Reputation: 4771

I would venture to guess you are running into the initialization order of statics issue, when AddUserData or RemoveUserData invoked from different compilation units. The issue I ran into when reviewing a singleton implementation here, with a link to a workaround, also discussed here.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182753

Actually, the error is much more likely to be this one:

The pthread_mutex_lock(), pthread_mutex_trylock() and pthread_mutex_unlock() functions may fail if:

[EINVAL]
The value specified by mutex does not refer to an initialised mutex object.

This is usually caused by memory corruption. You can try running under valgrind or a similar tool.

Upvotes: 3

Related Questions