How to do it...

  1. In the src/bin folder, create a file called bilocks.rs.
  2. Add the following code and run it with cargo run —bin bilocks:
1   extern crate futures;
2   extern crate futures_util;
3   
4   use futures::prelude::*;
5   use futures::executor::LocalPool;
6   use futures::task::{Context, LocalMap, Wake, Waker};
7   use futures_util::lock::BiLock;
8   
9   use std::sync::Arc;
10  
11  struct FakeWaker;
12  impl Wake for FakeWaker {
13    fn wake(_: &Arc) {}
14  }
15  
16  struct Reader {
17    lock: BiLock,
18  }
19  
20  struct Writer {
21    lock: BiLock,
22  }
23  
24  fn split() -> (Reader, Writer) {
25    let (a, b) = BiLock::new(0);
26    (Reader { lock: a }, Writer { lock: b })
27  }
29  fn main() {
30    let pool = LocalPool::new();
31    let mut exec = pool.executor();
32    let waker = Waker::from(Arc::new(FakeWaker));
33    let mut map = LocalMap::new();
34    let mut cx = Context::new(&mut map, &waker, &mut exec);
35  
36    let (reader, writer) = split();
37    println!("Lock should be ready for writer: {}",
38         writer.lock.poll_lock(&mut cx).is_ready());
39    println!("Lock should be ready for reader: {}",
40         reader.lock.poll_lock(&mut cx).is_ready());
41  
42    let mut writer_lock = match writer.lock.lock().poll(&mut 
cx).unwrap() { 43 Async::Ready(t) => t, 44 _ => panic!("We should be able to lock with writer"), 45 }; 46 47 println!("Lock should now be pending for reader: {}", 48 reader.lock.poll_lock(&mut cx).is_pending()); 49 *writer_lock = 123; 50 51 let mut lock = reader.lock.lock(); 52 match lock.poll(&mut cx).unwrap() { 53 Async::Ready(_) => { 54 panic!("The lock should not be lockable since writer has
already locked it!") 55 } 56 _ => println!("Couldn't lock with reader since writer has
already initiated the lock"), 57 }; 58 59 let writer = writer_lock.unlock(); 60 61 let reader_lock = match lock.poll(&mut cx).unwrap() { 62 Async::Ready(t) => t, 63 _ => panic!("We should be able to lock with reader"), 64 }; 65 66 println!("The new value for the lock is: {}", *reader_lock); 67 68 let reader = reader_lock.unlock(); 69 let reunited_value = reader.reunite(writer).unwrap(); 70 71 println!("After reuniting our locks, the final value is
still: {}", 72 reunited_value); 73 }
..................Content has been hidden....................

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