Created
August 5, 2019 21:01
-
-
Save cfsamson/dafcb5f6c2e58fe83826f55a5dc38261 to your computer and use it in GitHub Desktop.
Rust smart snippets
This file contains hidden or 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
trait DisplayTrait {} | |
struct DisplayImpl<'a> { context: &'a mut () } | |
struct ViewImpl; | |
impl<D: DisplayTrait> ViewTrait<D> for ViewImpl { | |
fn display(&mut self, _: &D) {} | |
} | |
trait ViewTrait<D: DisplayTrait> { | |
fn display(&mut self, display: &D); | |
} | |
impl<'a> DisplayTrait for DisplayImpl<'a> {} | |
fn main() { | |
let mut context = (); | |
let mut view: Box<dyn for<'a> ViewTrait<DisplayImpl<'a>>> = Box::new(ViewImpl); | |
for _ in 0..1 { | |
let d = DisplayImpl { context: &mut context }; | |
view.display(&d); | |
} | |
} |
This file contains hidden or 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
use std::sync::atomic::{AtomicBool, Ordering}; | |
use std::sync::Arc; | |
use std::thread; | |
struct PanicGuard(thread::Thread, Arc<AtomicBool>); | |
impl PanicGuard { | |
fn new(thr: thread::Thread, panic_flag: Arc<AtomicBool>) -> Self { | |
PanicGuard(thr, panic_flag) | |
} | |
} | |
impl Drop for PanicGuard { | |
fn drop(&mut self) { | |
if thread::panicking() { | |
self.1.store(true, Ordering::Relaxed); | |
self.0.unpark(); | |
} | |
} | |
} | |
fn main() { | |
// Need this to check if the wakeup is due to a panic in the child thread or just a spurious wakeup | |
// true only to allow the first thread to start | |
let child_is_panicking = Arc::new(AtomicBool::new(true)); | |
let mut counter = 1; | |
loop { | |
if (&child_is_panicking).compare_and_swap(true, false, Ordering::Relaxed) { | |
println!("Restarting child thread"); | |
let guard = PanicGuard::new(thread::current(), child_is_panicking.clone()); | |
thread::spawn(move || { | |
let _guard = guard; | |
thread::sleep(std::time::Duration::from_millis(2000)); | |
_guard.0.unpark(); | |
//thread::sleep(std::time::Duration::from_millis(500)); | |
panic!("Child panic"); | |
}); | |
} else { | |
println!("Spurious wakeup"); | |
} | |
println!("Parked for {}th time", counter); | |
thread::park(); | |
println!("Unparked for {}th time", counter); | |
counter += 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment