Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety and `const`

How does const (pointers, references and member functions) help with thread safety in C++?

like image 244
James Hopkin Avatar asked Dec 12 '08 09:12

James Hopkin


4 Answers

Const functions is not thread safe. Normaly, you can call const object methods from different threads concurrently, but if you call non const and const method from different threads you get race condition. Check this:

class Foo
{
    size_t size_;
public:
    ...
    size_t get_size() const
    {
        return size_
    }
};

class Bar
{
    boost::shared_ptr<Foo> foo_;
public:
    //accessor
    size_t get_size() const
    {
        size_t size = 0;
        if (foo_)
            size = foo_->size();
        return size;
    }
    //modifiers
    void init()
    {
        foo_ = new Foo;
    }

    void clear()
    {
        foo_ = boost::shared_ptr<Foo>();
    }
};

If somebody call init method, and then call clear and get_size methods concurrently, it will cause access violation. You must use read write lock idiom. Multiple accessors can be called at the same time, and only one modifier can be called at the same time. Exemple:

class Bar
{
    boost::shared_ptr<Foo> foo_;
    mutable tbb::spin_rw_mutex lock_;
public:
    //accessor
    size_t get_size() const
    {
        size_t size = 0;
        //lock modifiers
        rw_mutex_type::scoped_lock lock(mutex, false);
        if (foo_)
            size = foo_->size();
        return size;
    }
    //modifiers
    void init()
    {
        //lock accessor and modifiers
        rw_mutex_type::scoped_lock lock(mutex, true);
        foo_ = new Foo;
    }

    void clear()
    {
        //lock accessor and modifiers
        rw_mutex_type::scoped_lock lock(mutex, true);
        foo_ = boost::shared_ptr<Foo>();
    }
};

tbb::spin_rw_lock is a mutex class from threading builing blocks library

like image 146
Evgeny Lazin Avatar answered Nov 05 '22 00:11

Evgeny Lazin


Any immutable (that is, unchangable) data is inherently thread safe - there's no risk for multiple threads concurrently reading the same read-only data because it's never going to change!

Marking a variable as const in C++ makes it read-only and thus thread safe.

like image 42
Mark Pim Avatar answered Nov 18 '22 18:11

Mark Pim


The main problem with multiple threads is mutability. const restricts this, but since you can cast away the const-ness, it's not foolproof.

like image 6
Brian Rasmussen Avatar answered Nov 18 '22 19:11

Brian Rasmussen


A const member function shouldn't change state which makes it safe to call from multiple threads at the same time. However thread safety is not the purpose of const and C++ provides the mutable keyword and const_cast meaning that const does not actually guarantee thread safety and shouldn't be relied on for this purpose.

like image 6
Patrick Avatar answered Nov 18 '22 18:11

Patrick