How to do it...

  1. In the folder bin, create a file called rw_lock.rs.

  2. Add the following code and run it with cargo run --bin rwlock:

1 use std::sync::{Arc, RwLock};
2 use std::thread;
3
4 fn main() {
5 // An RwLock works like the RefCell, but blocks the current
6 // thread if the resource is unavailable
7 let resource = Arc::new(RwLock::new("Hello
World!".to_string()));
8
9 // The reader_a thread will print the current content of
10 // our resource fourty times
11 let reader_a = {
12 let resource = resource.clone();
13 thread::spawn(move || {
14 for _ in 0..40 {
15 // Lock resource for reading access
16 let resource = resource
17 .read()
18 .expect("Failed to lock resource for reading");
19 println!("Reader A says: {}", resource);
20 }
21 })
22 };
23
24 // The reader_b thread will print the current content of
25 // our resource fourty times as well. Because RwLock allows
26 // multiple readers, it will execute at the same time as
reader_a
27 let reader_b = {
28 let resource = resource.clone();
29 thread::spawn(move || {
30 for _ in 0..40 {
31 // Lock resource for reading access
32 let resource = resource
33 .read()
34 .expect("Failed to lock resource for reading");
35 println!("Reader B says: {}", resource);
36 }
37 })
38 };
39
40 // The writer thread will modify the resource ten times.
41 // Because RwLock enforces Rust's access rules
42 // (multiple readers xor one writer), this thread will wait
until
43 // thread_a and thread_b are not using the resource and then
block
44 // them both until its done.
45 let writer = {
46 let resource = resource.clone();
47 thread::spawn(move || {
48 for _ in 0..10 {
49 // Lock resource for writing access
50 let mut resource = resource
51 .write()
52 .expect("Failed to lock resource for writing");
53
54 resource.push('!'),
55 }
56 })
57 };
58
59 reader_a.join().expect("Reader A panicked");
60 reader_b.join().expect("Reader B panicked");
61 writer.join().expect("Writer panicked");
62 }
..................Content has been hidden....................

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