Skip to content

Commit a341bc5

Browse files
committed
samples: philosophers: Migrate Mutex to const constructor
With Mutex having a const constructor, simplify the initializaion, and use a simple static for the Stats container. Signed-off-by: David Brown <[email protected]>
1 parent 5000f45 commit a341bc5

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

samples/philosophers/src/lib.rs

+16-9
Original file line numberDiff line numberDiff line change
@@ -68,22 +68,18 @@ extern "C" fn rust_main() {
6868
printkln!("Hello world from Rust on {}", zephyr::kconfig::CONFIG_BOARD);
6969
printkln!("Time tick: {}", zephyr::time::SYS_FREQUENCY);
7070

71-
let stats = Arc::new(Mutex::new_from(
72-
Stats::default(),
73-
STAT_MUTEX.init_once(()).unwrap(),
74-
));
71+
let stats = &STAT_MUTEX;
7572

7673
let syncers = get_syncer();
7774

7875
printkln!("Pre fork");
7976

8077
for (i, syncer) in (0..NUM_PHIL).zip(syncers.into_iter()) {
81-
let child_stat = stats.clone();
8278
let thread = PHIL_THREADS[i]
8379
.init_once(PHIL_STACKS[i].init_once(()).unwrap())
8480
.unwrap();
8581
thread.spawn(move || {
86-
phil_thread(i, syncer, child_stat);
82+
phil_thread(i, syncer, stats);
8783
});
8884
}
8985

@@ -133,7 +129,7 @@ fn get_syncer() -> Vec<Arc<dyn ForkSync>> {
133129
get_channel_syncer()
134130
}
135131

136-
fn phil_thread(n: usize, syncer: Arc<dyn ForkSync>, stats: Arc<Mutex<Stats>>) {
132+
fn phil_thread(n: usize, syncer: Arc<dyn ForkSync>, stats: &'static Mutex<Stats>) {
137133
printkln!("Child {} started: {:?}", n, syncer);
138134

139135
// Determine our two forks.
@@ -191,6 +187,17 @@ struct Stats {
191187
thinking: [u64; NUM_PHIL],
192188
}
193189

190+
impl Stats {
191+
/// Const constructor to allow for static initializaion.
192+
pub const fn new() -> Self {
193+
Self {
194+
count: [0; NUM_PHIL],
195+
eating: [0; NUM_PHIL],
196+
thinking: [0; NUM_PHIL],
197+
}
198+
}
199+
}
200+
194201
impl Stats {
195202
fn record_eat(&mut self, index: usize, time: Duration) {
196203
self.eating[index] += time.to_millis();
@@ -211,9 +218,9 @@ impl Stats {
211218
}
212219
}
213220

221+
static STAT_MUTEX: Mutex<Stats> = Mutex::new(Stats::new());
222+
214223
kobj_define! {
215224
static PHIL_THREADS: [StaticThread; NUM_PHIL];
216225
static PHIL_STACKS: [ThreadStack<PHIL_STACK_SIZE>; NUM_PHIL];
217-
218-
static STAT_MUTEX: StaticMutex;
219226
}

samples/philosophers/src/sysmutex.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub struct SysMutexSync {
2323
impl SysMutexSync {
2424
#[allow(dead_code)]
2525
pub fn new() -> SysMutexSync {
26-
let locks = [(); NUM_PHIL].each_ref().map(|()| Mutex::new().unwrap());
26+
let locks = [(); NUM_PHIL].each_ref().map(|()| Mutex::new());
2727
SysMutexSync { locks }
2828
}
2929
}

0 commit comments

Comments
 (0)