Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2024
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.85 KB | Source Code | 0 0
  1. use lazy_static::lazy_static;
  2. use singletone::Singletone;
  3.  
  4. pub mod singletone {
  5.     use std::ops::Deref;
  6.  
  7.     #[derive(Debug)]
  8.     pub struct Singletone<T>(*mut T);
  9.  
  10.     impl<T> Singletone<T> {
  11.         pub fn new(t: T) -> Singletone<T> {
  12.             Singletone(Box::leak(Box::new(t)))
  13.         }
  14.     }
  15.  
  16.     // SAFETY: it's always safe to Send, because we hold only a leaked pointer.
  17.     unsafe impl<T> Send for Singletone<T> {}
  18.  
  19.     // SAFETY: we don't provide DerefMut, so we can assume that it's safe to impl Sync.
  20.     unsafe impl<T> Sync for Singletone<T> {}
  21.  
  22.     impl<T> Deref for Singletone<T> {
  23.         type Target = T;
  24.  
  25.         fn deref(&self) -> &Self::Target {
  26.             unsafe { &*self.0 }
  27.         }
  28.     }
  29.  
  30.     impl<T> Clone for Singletone<T> {
  31.         fn clone(&self) -> Self {
  32.             Singletone(self.0)
  33.         }
  34.     }
  35.  
  36.     impl<T> Copy for Singletone<T> {}
  37. }
  38.  
  39. struct Worker;
  40.  
  41. impl Worker {
  42.     async fn work(&self) {
  43.         tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
  44.         println!("Work done");
  45.     }
  46. }
  47.  
  48. lazy_static! {
  49.     static ref SINGLETONE: singletone::Singletone<Worker> = singletone::Singletone::new(Worker);
  50. }
  51.  
  52. #[tokio::main]
  53. async fn main() {
  54.     let mut jobs = vec![];
  55.     {
  56.         // use singletone
  57.         let singletone = Singletone::new(Worker);
  58.  
  59.         // or in a such way with lazy_static
  60.         // let singletone = &SINGLETONE;
  61.  
  62.         jobs.push(tokio::spawn(async move {
  63.             singletone.work().await;
  64.         }));
  65.         jobs.push(tokio::spawn(async move {
  66.             singletone.work().await;
  67.         }));
  68.  
  69.         // Notice that singleton doesn't get destroyed after end of this scope
  70.     }
  71.  
  72.     let t2 = jobs.pop().unwrap();
  73.     let t1 = jobs.pop().unwrap();
  74.     let (t1, t2) = tokio::join!(t1, t2);
  75.     t1.unwrap();
  76.     t2.unwrap();
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement