shared_ptr in multi-threaded app

I have a problem with using std and boost shared_ptr in multi-threaded application. It is well illustrated with this test:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <memory>
#include <omp.h>
int main () {
    for (int i = 0; ; i++) {
        std::shared_ptr<int> p_source (new int (i));
#pragma omp parallel default(shared) num_threads (2)
        {
            int ithr = omp_get_thread_num ();
            if (ithr == 0) {
                std::shared_ptr <int> p = p_source;
            } else {
                p_source = std::make_shared<int> (0);
                // p_source.reset (new int (0));
            }
        }
    }
    return 0;
}


At some arbitrary iteration the test crashes on access to an already freed sp_counted_block on Linux (RH 6.4). On Windows it works fine. The same test rewritten with boost pointer crashes on both platforms.

Is it supposed to work?
Last edited on
it isn't supposed to work: the only special guarantee given by shared_ptr is that different std::shared_ptrs can be accessed using mutable operations even if they share the control block

In this case, the same p_source is modified in one thread and read from in another thread, that's a data race. This is why atomic operations for shared pointers exist: http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic
Thanks. It helped.
Topic archived. No new replies allowed.