-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a5e0059
commit bc74bdf
Showing
3 changed files
with
102 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
[package] | ||
name = "ysos_counter" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[dependencies] | ||
lib = { path="../../lib", package="yslib"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
#![no_std] | ||
#![no_main] | ||
|
||
use lib::*; | ||
|
||
extern crate lib; | ||
|
||
const THREAD_COUNT: usize = 8; | ||
static mut COUNTER: isize = 0; | ||
|
||
fn main() -> isize { | ||
let mut pids = [0u16; THREAD_COUNT]; | ||
|
||
for i in 0..THREAD_COUNT { | ||
let pid = sys_fork(); | ||
if pid == 0 { | ||
do_counter_inc(); | ||
sys_exit(0); | ||
} else { | ||
pids[i] = pid; // only parent knows child's pid | ||
} | ||
} | ||
|
||
let cpid = sys_get_pid(); | ||
println!("process #{} holds threads: {:?}", cpid, &pids); | ||
sys_stat(); | ||
|
||
for i in 0..THREAD_COUNT { | ||
println!("#{} waiting for #{}...", cpid, pids[i]); | ||
sys_wait_pid(pids[i]); | ||
} | ||
|
||
println!("COUNTER result: {}", unsafe { COUNTER }); | ||
|
||
0 | ||
} | ||
|
||
fn do_counter_inc() { | ||
for _ in 0..100 { | ||
// FIXME: protect the critical section | ||
inc_counter(); | ||
} | ||
} | ||
|
||
/// Increment the counter | ||
/// | ||
/// this function simulate a critical section by delay | ||
/// DO NOT MODIFY THIS FUNCTION | ||
fn inc_counter() { | ||
unsafe { | ||
delay(); | ||
let mut val = COUNTER; | ||
delay(); | ||
val += 1; | ||
delay(); | ||
COUNTER = val; | ||
} | ||
} | ||
|
||
#[inline(never)] | ||
#[no_mangle] | ||
fn delay() { | ||
for _ in 0..0x100 { | ||
core::hint::spin_loop(); | ||
} | ||
} | ||
|
||
entry!(main); |