Skip to content

A thread with a lifetime. Divide a value into master and slave. After the lifetime of the master value ends, the slave value will not be accessible.

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

liangyongrui/lifetime-thread

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Lifetime Thread

A lock-free thread with a lifetime. Divide a value into master and slave. After the lifetime of the master value ends, the slave value will not be accessible.


Introduction

A lock-free thread with a lifetime. Divide a value into master and slave. After the lifetime of the master value ends, the slave value will not be accessible.

scenes to be used:

  • An operation needs to be performed in the background, but the lifetime is not static
  • ...

Basic usage

use std::{thread, time::Duration};

#[test]
fn it_works() {
    let s = "xxx";
    let outer = lifetime_thread::spawn(s, |inner| {
        println!("begin");
        while let Some(t) = inner.get() {
            println!("ok! {}", t);
            assert_eq!(*t, "xxx");
            thread::sleep(Duration::from_millis(1));
        }
        println!("over")
    });
    thread::sleep(Duration::from_millis(10));
    assert_eq!(*outer, "xxx")
}

#[tokio::test]
async fn async_works() {
    let s = "xxx";
    let outer = lifetime_thread::async_spawn(s, |inner| async move {
        println!("begin");
        while let Some(t) = inner.get() {
            println!("ok! {}", t);
            assert_eq!(*t, "xxx");
            tokio::time::sleep(Duration::from_millis(1)).await;
        }
        println!("over")
    });
    tokio::time::sleep(Duration::from_millis(10)).await;
    assert_eq!(*outer, "xxx");
    drop(outer);
}

output:

begin
ok! xxx
ok! xxx
...
...
ok! xxx
over

Features

  • Different runtime
    • sync (Multithreading): lifetime_thread::spawn
    • tokio: lifetime_thread::async_spawn

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions

About

A thread with a lifetime. Divide a value into master and slave. After the lifetime of the master value ends, the slave value will not be accessible.

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages