Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use lazy_static::lazy_static;
- use singletone::Singletone;
- pub mod singletone {
- use std::ops::Deref;
- #[derive(Debug)]
- pub struct Singletone<T>(*mut T);
- impl<T> Singletone<T> {
- pub fn new(t: T) -> Singletone<T> {
- Singletone(Box::leak(Box::new(t)))
- }
- }
- // SAFETY: it's always safe to Send, because we hold only a leaked pointer.
- unsafe impl<T> Send for Singletone<T> {}
- // SAFETY: we don't provide DerefMut, so we can assume that it's safe to impl Sync.
- unsafe impl<T> Sync for Singletone<T> {}
- impl<T> Deref for Singletone<T> {
- type Target = T;
- fn deref(&self) -> &Self::Target {
- unsafe { &*self.0 }
- }
- }
- impl<T> Clone for Singletone<T> {
- fn clone(&self) -> Self {
- Singletone(self.0)
- }
- }
- impl<T> Copy for Singletone<T> {}
- }
- struct Worker;
- impl Worker {
- async fn work(&self) {
- tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
- println!("Work done");
- }
- }
- lazy_static! {
- static ref SINGLETONE: singletone::Singletone<Worker> = singletone::Singletone::new(Worker);
- }
- #[tokio::main]
- async fn main() {
- let mut jobs = vec![];
- {
- // use singletone
- let singletone = Singletone::new(Worker);
- // or in a such way with lazy_static
- // let singletone = &SINGLETONE;
- jobs.push(tokio::spawn(async move {
- singletone.work().await;
- }));
- jobs.push(tokio::spawn(async move {
- singletone.work().await;
- }));
- // Notice that singleton doesn't get destroyed after end of this scope
- }
- let t2 = jobs.pop().unwrap();
- let t1 = jobs.pop().unwrap();
- let (t1, t2) = tokio::join!(t1, t2);
- t1.unwrap();
- t2.unwrap();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement