I made a class in C++ today and I'm surprised it's not something that was already in the standard library

basically it's a class called LockBox<C> that holds an instance of C which is inaccessible, unless you use the Unlocker<C> class like so:

C instance;
LockBox<C> box(instance);
*pass box around to different threads*
*later in some thread*
Unlocker<C> instance(box);

and it's thread safe C:

Show thread

Unlocker<C> is a friend class that locks a mutex inside of LockBox<C> and acts as a lock_guard for that mutex. it also uses the -> and * operators to let you access members of the underlying C class

Show thread

you can also make the Unlocker const so you can only access const members of C

Show thread

there is a wrinkle because there is no copy constructor since std::mutex has no copy constructor, but you could potentially get around this by wrapping the mutex in a std::shared_ptr

Show thread

@SuricrasiaOnline why did they call it boost and not "I can't believe it's not in std yet"

@SuricrasiaOnline so it's kinda like rust's idea of mutexes?

I like this, and agree, why the heck isn't it in std

@k thankfully it's not too difficult to implement yourself, you just need to piece together std::mutex and std::lock_guard together in a particular way

@k @SuricrasiaOnline it's almost like, until rust came around no systems programming language thought about making threading… safe?!

Sign in to participate in the conversation

Cybrespace is an instance of Mastodon, a social network based on open web protocols and free, open-source software. It is decentralized like e-mail.