Boost lock_guard<boost::mutex> Throws EINVAL Exception

让人想犯罪 __ 提交于 2019-12-23 23:15:32

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7651501/boost-lock-guardboostmutex-throws-einval-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!