/
integration_test.rs
103 lines (80 loc) · 2.72 KB
/
integration_test.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use std::{
sync::{Arc, Mutex},
thread::spawn,
};
use lazy_static::lazy_static;
use rand::Rng;
use singly::Singleton;
struct ExamScore(Vec<i32>);
// ------ For Normal situation in Multi Threaded Environment ---------
#[test]
fn multi_thread_situation_reading() {
let mut instance = Singleton::new();
let scores: Vec<_> = (0..200)
.map(|_| {
let mut rng = rand::thread_rng();
rng.gen_range(0..100)
})
.collect();
let expected_sum = scores.iter().fold(0, |acc, score| acc + score);
let expected_mean = expected_sum / scores.len() as i32;
instance.set(Arc::new(ExamScore(scores)));
let scores_clone1 = Arc::clone(instance.get::<Arc<ExamScore>>());
let scores_clone2 = Arc::clone(instance.get::<Arc<ExamScore>>());
let thread1 = spawn(move || (*scores_clone1).0.iter().fold(0, |acc, score| acc + score));
let thread2 = spawn(move || {
(*scores_clone2).0.iter().fold(0, |acc, score| acc + score) / scores_clone2.0.len() as i32
});
let result = thread1.join().unwrap();
assert_eq!(expected_sum, result);
let result = thread2.join().unwrap();
assert_eq!(expected_mean, result);
}
struct Counter(i32);
type ArcMutexCounter = Arc<Mutex<Counter>>;
#[test]
fn multi_thread_situation_counter() {
let mut instance = Singleton::new();
let counter = Arc::new(Mutex::new(Counter(0)));
instance.set(counter);
let mut handles = vec![];
for _ in 0..10 {
let counter_clone = Arc::clone(instance.get::<ArcMutexCounter>());
let handle = spawn(move || {
let mut counter = counter_clone.lock().unwrap();
(*counter).0 += 1;
});
handles.push(handle);
}
let _ = handles
.into_iter()
.map(|handle| handle.join())
.collect::<Result<Vec<_>, _>>();
let counter = instance.get::<ArcMutexCounter>().lock().unwrap().0;
assert_eq!(counter, 10);
}
// ------ For Static Usage in Multi Threaded Environment ---------
lazy_static! {
static ref SINGLETON_INSTANCE: Mutex<Singleton> = Mutex::new(Singleton::new());
}
#[test]
fn static_test() {
let counter = Counter(0);
SINGLETON_INSTANCE.lock().unwrap().set(counter);
let mut handles = vec![];
for _ in 0..10 {
let handle = spawn(move || {
let mut instance = SINGLETON_INSTANCE.lock().unwrap();
instance
.try_get_mut::<Counter>()
.map(|counter| (*counter).0 += 1);
});
handles.push(handle);
}
let _ = handles
.into_iter()
.map(|handle| handle.join())
.collect::<Result<Vec<_>, _>>();
let counter = SINGLETON_INSTANCE.lock().unwrap().get::<Counter>().0;
assert_eq!(counter, 10);
}