Created
May 12, 2016 19:12
-
-
Save anonymous/4ce669d0a68ac3d4731c4d440cc39dd6 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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
// #![allow(dead_code)] | |
// #![allow(unused_variables)] | |
// #![allow(unused_mut)] | |
use std::sync::Mutex; | |
use std::sync::Arc; | |
use std::collections::VecDeque; | |
use std::thread; | |
use std::ops::Deref; | |
#[derive(Clone)] | |
#[derive(Debug)] | |
enum Message {A(i32), B(String)} | |
#[derive(Default)] | |
struct MBox (Mutex<VecDeque<Message>>); | |
impl Deref for MBox { | |
type Target = Mutex<VecDeque<Message>>; | |
fn deref(&self) -> &Self::Target {&self.0} | |
} | |
impl MBox { | |
fn send(&self, msg : Message) { | |
self.lock().unwrap().push_back(msg); | |
} | |
fn try_recv(&self) -> Option<Message> { | |
self.lock().unwrap().pop_front() | |
} | |
fn recv(&self) -> Message { | |
loop { | |
if let Some(x) = self.try_recv() { | |
return x; | |
} | |
thread::park(); | |
} | |
} | |
} | |
/* | |
impl Default for MBox { | |
fn default() -> MBox { | |
MBox(Mutex::new(Default::default())) | |
} | |
} | |
*/ | |
thread_local!(static MBOX : MBox = Default::default()); | |
fn main() { | |
MBOX.with(|mbox| { | |
mbox.send(Message::A(2)); | |
println!("Hello"); | |
}); | |
MBOX.with(|mbox| { | |
let msg = mbox.try_recv(); | |
println!("Hello {:?}", msg); | |
}); | |
let mbox2 : Arc<MBox> = Default::default(); | |
let mb2 = mbox2.clone(); | |
let x = thread::spawn( move || { | |
thread::current().unpark(); | |
thread::sleep_ms(20); | |
let msg = mb2.recv(); | |
println!("Hello2 {:?}", msg); | |
msg | |
}); | |
//x.thread().unpark(); | |
//x.thread().unpark(); | |
{let t = x.thread().clone(); | |
thread::spawn(move || { | |
thread::sleep_ms(500); | |
mbox2.send(Message::B("Hello".to_string())); | |
println!("Hello2"); | |
t.unpark(); | |
});} | |
let result = x.join(); | |
println!("Result: {:?}", result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment