uazu / qcell

Statically-checked alternatives to RefCell and RwLock
Apache License 2.0
356 stars 22 forks source link

Add `TCellOwner::try_new` and `TCellOwner::wait_for_new` #15

Closed michiel-de-muynck closed 3 years ago

michiel-de-muynck commented 3 years ago

This commit adds two new functions:

Internally, this was implemented using a single static Condvar. If a wait_for_new call finds that a TCellOwner with its marker type Q already exists, it waits for this Condvar. Any time a TCellOwner is dropped, all threads waiting for this Condvar are woken up and check if the TCellOwner that was dropped was their marker type Q.

Performance-wise, this means that dropping a TCellOwner is now a tiny bit slower (the Condvar::notify_all call). This should be completely insignificant for any realistic use case. The performance of every other method (including TCellOwner::new) is unaffected. TCellOwner::wait_for_new is just as fast as TCellOwner::new if there is no need to wait.

uazu commented 3 years ago

Many thanks for this! It all looks fine, and matches the existing style so nothing to fix up.

One thing that occurred to me, looking at the 100 thread test, is that by quickly creating and dropping an ACellOwner, you're effectively getting a temporary lock on all the ACells. I don't think we want to encourage this pattern. It would be better for the caller to create a single long-lived ACellOwner wrapped in a RwLock or Mutex. Maybe I'll add a note somewhere before releasing the new version.

I have a few other small-ish changes that I want to do before pushing the next version out to crates.io, but I won't leave it too long.

michiel-de-muynck commented 3 years ago

The intent of that test was just to stress-test that everything still works in an extreme scenario, not necessarily as a recommendation that users should use the API like that.

uazu commented 3 years ago

Yes, that's fine. I just want to make sure that I point crate users in the right direction, in case they independently come up with that pattern, not realizing that it is sub-optimal. Anyway, thanks again!