]> git.lizzy.rs Git - rust.git/blob - tests/run-pass/concurrency/locks.rs
Add concurrency tests.
[rust.git] / tests / run-pass / concurrency / locks.rs
1 // ignore-windows
2
3 use std::sync::{Arc, Mutex, RwLock};
4 use std::thread;
5
6 fn check_mutex() {
7     let data = Arc::new(Mutex::new(0));
8     let mut threads = Vec::new();
9
10     for _ in 0..3 {
11         let data = Arc::clone(&data);
12         let thread = thread::spawn(move || {
13             let mut data = data.lock().unwrap();
14             *data += 1;
15         });
16         threads.push(thread);
17     }
18
19     for thread in threads {
20         thread.join().unwrap();
21     }
22
23     assert!(data.try_lock().is_ok());
24
25     let data = Arc::try_unwrap(data).unwrap().into_inner().unwrap();
26     assert_eq!(data, 3);
27 }
28
29 fn check_rwlock_write() {
30     let data = Arc::new(RwLock::new(0));
31     let mut threads = Vec::new();
32
33     for _ in 0..3 {
34         let data = Arc::clone(&data);
35         let thread = thread::spawn(move || {
36             let mut data = data.write().unwrap();
37             *data += 1;
38         });
39         threads.push(thread);
40     }
41
42     for thread in threads {
43         thread.join().unwrap();
44     }
45
46     assert!(data.try_write().is_ok());
47
48     let data = Arc::try_unwrap(data).unwrap().into_inner().unwrap();
49     assert_eq!(data, 3);
50 }
51
52 fn check_rwlock_read_no_deadlock() {
53     let l1 = Arc::new(RwLock::new(0));
54     let l2 = Arc::new(RwLock::new(0));
55
56     let l1_copy = Arc::clone(&l1);
57     let l2_copy = Arc::clone(&l2);
58     let _guard1 = l1.read().unwrap();
59     let handle = thread::spawn(move || {
60         let _guard2 = l2_copy.read().unwrap();
61         thread::yield_now();
62         let _guard1 = l1_copy.read().unwrap();
63     });
64     thread::yield_now();
65     let _guard2 = l2.read().unwrap();
66     handle.join().unwrap();
67 }
68
69 fn main() {
70     check_mutex();
71     check_rwlock_write();
72     check_rwlock_read_no_deadlock();
73 }