How it works...

  • First, we need to implement a fake futures::task::Waker for when we create a new context (this is what our FakeWaker structure is for on lines 11 through 14)
  • Since BiLocks require two owners, we will divide the ownership into two different structures, called Reader<T> (on lines 16 through 18) and Writer<T> (on lines 20 through 22)
  • Our split() -> (Reader<u32>, Writer<u32>) function is just to structure/organize our code a bit better, and when calling BiLock::new(t: T) the return type is a tuple of two futures_util::lock::BiLock elements

Now that the preliminary code has been explained, let's dive into our main() function:

  • On lines 30 through 34 we set up a new LocalPool, LocalExecutor, Waker (FakeWaker), and a LocalMap (map storage of local data within tasks) for creating a new Context, since we will be polling our locks manually for demonstration purposes.
  • Lines 38 and 40 use the futures_util::lock::BiLock::poll_lock function, which returns an Async<futures_util::lock::BiLockGuard<T>> value if the lock is available. If the lock is not available then the function will return Async::Pending. The lock (the BiLockGuard<T>) will unlock when the reference is dropped.
  • On line 42 we execute writer.lock.lock(), which will block the lock and a BiLockAcquire<T> will be returned, which is a future that can be polled. When BiLockAcquire is polled, a Poll<BiLockAcquired<T>, ()> value is returned and that value can be dereferenced mutably.
  • On line 48, we can now see that the lock is currently in an Async::Pending state, which would not allow us to lock the BiLock again, as shown on lines 51 through 57.
  • After modifying our lock's value (line 49), we should now unlock it (line 59) so that the other owner can reference it (lines 61 through 64).
  • When we call BiLockAcquired::unlock() (line 68), the original BiLock<T> is returned and the lock is officially unlocked.
  • On line 69 we perform futures_util::lock::BiLock::reunite(other: T), which recovers the value of the lock and destroys the two halves of the BiLock references (presuming that T is the other half of the BiLock from the BiLock::new() call).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.35.72