• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 647
  • Last Modified:

handling pthread_mutex_lock, pthread_mutex_unlock errors

Hi Experts,

Assuming I have the following code for creating a singleton, how can I handle if error is returned from pthread functions?  What is a good way to handle it.

Manager * Manager::getInstance()
    if (_instance == 0)
        if (_instance == 0) // double checked
            _instance = new Manager();
    return _instance;

Open in new window

If I have a setter function like below, what could be the better way to handle pthread errors.

void DataHolder::setSomething(int data)
    m_data = data;

Open in new window

1 Solution
>> What is a good way to handle it.

Drastically reduce the chance errors might be returned by :

1) ensuring that the mutex is properly initialized before trying to use it.
2) being careful with recursive locking (your current code doesn't show that, unless the Manager constructor calls Manager::getInstance, or the same mutex is used outside of Manager::getInstance, for different purposes eg. -- don't do either of this).
3) ensuring there are matching unlock's for every lock, and an unlock is not performed if the current thread doesn't own the lock.
4) being careful with thread priorities (don't have them too high) together with PTHREAD_PRIO_PROTECT.

If all these conditions are true, then an error can really only occur if something is seriously wrong, in which case, you can do something drastic like halt the application, or ...

>> If I have a setter function like below, what could be the better way to handle pthread errors.

Same rules as above. Being extra careful about recursively locking the mutex.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

A proven path to a career in data science

At Springboard, we know how to get you a job in data science. With Springboard’s Data Science Career Track, you’ll master data science  with a curriculum built by industry experts. You’ll work on real projects, and get 1-on-1 mentorship from a data scientist.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now