Skip to content

Commit 8bc135d

Browse files
committed
02_ownership: add aliasing-xor-mutability example
1 parent 39ff594 commit 8bc135d

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[package]
2+
name = "aliasing_xor_mutability"
3+
version = "0.1.0"
4+
edition = "2021"
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
fn next_int() -> i32 {
2+
42
3+
}
4+
5+
struct Data(i32);
6+
impl Data {
7+
fn new() -> Self {
8+
Self(0)
9+
}
10+
11+
fn read(&self) -> i32 { self.0 }
12+
13+
fn write(&mut self, n: i32) { self.0 = n }
14+
}
15+
16+
fn thread1(shared_data: &mut Data) {
17+
loop {
18+
shared_data.write(next_int());
19+
}
20+
}
21+
22+
fn thread2(shared_data: &Data) {
23+
loop {
24+
println!("{}", shared_data.read());
25+
}
26+
}
27+
28+
fn main() {
29+
let mut shared_data = Data::new();
30+
31+
std::thread::scope(|s| {
32+
let t1 = s.spawn(|| {
33+
thread1(&mut shared_data);
34+
});
35+
let t2 = s.spawn(|| {
36+
thread2(&shared_data);
37+
});
38+
});
39+
}

0 commit comments

Comments
 (0)