concurrency options
parent
5b9dbb0ce4
commit
df5983d26d
@ -0,0 +1,2 @@
|
||||
process_a
|
||||
process_b
|
@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "Chapter8"
|
||||
version = "1.0.0"
|
||||
|
||||
[dependencies]
|
||||
nix = "0.10"
|
||||
|
||||
[[bin]]
|
||||
name = "process_a"
|
||||
path = "process_a.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "process_b"
|
||||
path = "process_b.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "fork1"
|
||||
path = "fork1.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "fork2"
|
||||
path = "fork2.rs"
|
@ -0,0 +1,26 @@
|
||||
extern crate nix;
|
||||
use nix::unistd::{fork,ForkResult};
|
||||
use std::{thread,time};
|
||||
use std::process;
|
||||
|
||||
fn main() {
|
||||
let mut children = Vec::new();
|
||||
for _ in 0..3 {
|
||||
match fork().expect("fork failed") {
|
||||
ForkResult::Parent{ child: pid } => { children.push(pid); }
|
||||
ForkResult::Child => {
|
||||
let t = time::Duration::from_millis(1000);
|
||||
loop {
|
||||
println!("child process #{}", process::id());
|
||||
thread::sleep(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let t = time::Duration::from_millis(1000);
|
||||
loop {
|
||||
println!("parent process #{}", process::id());
|
||||
thread::sleep(t);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
extern crate nix;
|
||||
use nix::unistd::{fork};
|
||||
use std::{thread,time};
|
||||
|
||||
fn main() {
|
||||
let mut big_data: Vec<u8> = Vec::with_capacity(200000000);
|
||||
big_data.push(1);
|
||||
big_data.push(2);
|
||||
big_data.push(3);
|
||||
|
||||
//Both sides of the fork, will continue to fork
|
||||
//This is called a fork bomb
|
||||
for _ in 0..9 {
|
||||
fork().expect("fork failed");
|
||||
}
|
||||
//2^9 = 512
|
||||
|
||||
let t = time::Duration::from_millis(1000);
|
||||
loop {
|
||||
big_data[2];
|
||||
thread::sleep(t);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
use std::process::Command;
|
||||
use std::env::current_exe;
|
||||
|
||||
fn main() {
|
||||
let mut path = current_exe()
|
||||
.expect("could not find current executable");
|
||||
path.pop();
|
||||
path.push("process_b");
|
||||
|
||||
let mut children = Vec::new();
|
||||
for _ in 0..3 {
|
||||
children.push(
|
||||
Command::new(path.as_os_str())
|
||||
.spawn()
|
||||
.expect("failed to execute process")
|
||||
);
|
||||
}
|
||||
|
||||
for mut c in children {
|
||||
c.wait()
|
||||
.expect("failed to wait on child");
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
use std::{thread,time};
|
||||
use std::process;
|
||||
|
||||
fn main() {
|
||||
let t = time::Duration::from_millis(1000);
|
||||
loop {
|
||||
println!("process b #{}", process::id());
|
||||
thread::sleep(t);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue