Hacker News new | ask | show | jobs
by duneroadrunner 3141 days ago
It's arguably even a little bit nicer in SaferCPlusPlus[1]:

    template<typename TVectorPointer>
    void write_foo(TVectorPointer vec_ptr) {
        (*vec_ptr)[3] += 1;
    }
    
    template<typename TVectorPointer>
    auto read_foo(TVectorPointer vec_ptr) {
        return (*vec_ptr)[7];
    }
    
    template<typename TVectorAccessRequester>
    void use_shared_vector(TVectorAccessRequester vec_ar) {
        {
            // obtain a non-const pointer to the vector from the "access requester"
            // blocking if necessary
            auto wl_ptr = vec_ar.writelock_ptr();

            write_foo(wl_ptr);

            // the pointer owns a lock on the vector so as long as the pointer
            // exists it is safe and valid to use
        }

        // obtaining and using a const pointer to the vector
        auto res1 = read_foo(vec_ar.readlock_ptr());
        
        // without a "lock pointer" obtained from an access requester, there is no way
        // to access, or even refer to the shared vector, so you can't access it in an
        // unsafe manner
    }
[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus#asynchronou...