News for hackers. Stuff that matters.
Re:MutexProtected: A C++ Pattern for Easier Concurrency by simplotek on Thursday April 06, 2023 @08:32AM (#35467479)
> Neat idea.

I don't agree. It sounds like a higher level path to deadlocks.

> Maybe instead combine the two ideas. MutexProtected<T> but can be locked with MutexProtected<T>::lock() which returns a MutexLocked<T> object. That object then cleans up the lock when it goes out of scope, and also provides direct access to the enclosed type.

It sounds like you're trying to invent std::lock_guard with extra steps.

https://en.cppreference.com/w/cpp/thread/lock_guard

Re:MutexProtected: A C++ Pattern for Easier Concurrency by jmull on Thursday April 06, 2023 @09:01AM (#35467780)
> It sounds like ... std::lock_guard with extra steps.

I'm not the previous poster, but I think they are still suggesting that the value not be accessible until the lock is acquired.

Something like this (Apologies, I haven't done C++ is a long time and this is just off the top of my head. It's based on the example from the lock_guard example for the sake of comparison):

    guardthing<int> guarded_value;

    void safe_increment()
    {
        auto lock = guarded_value.lock();
        lock.value += 1;

        std::cout << "value: " << value << "; in thread #"
                  << std::this_thread::get_id() << '\n';
     
        // the mutex in guarded_value is automatically released when lock
        // goes out of scope
    }
Re:MutexProtected: A C++ Pattern for Easier Concurrency by Blackthorn on Thursday April 06, 2023 @10:28AM (#35468722)
> It sounds like you're trying to invent std::lock_guard with extra steps.

No, because lock_guard doesn't guard fields. lock_guard is simply the RAII option they were talking about in the article.