#Async Global Signal Write Locks

1 messages · Page 1 of 1 (latest)

tight dune
#

I am using a global signal in an event handler like the following:

let mut value = VALUE.write();
match &mut value {
    Variant1 => {
        spawn(async move {
            let new_value = do_something().await;
            *VALUE.write() = Variant3;
        });
    }
    Variant2(inner) => *inner += 123
    ... // lots of other variants
}

Is this okay?

My concerns come from the following:

  1. Do read and write borrows on global signals wait until they can get a borrow, and only error when I try to get an incompatible borrow on the same thread?
  2. Do I need to worry about deadlocks?
  3. Aren't global signals not safe across threads since they are UnsyncStorage?

For context, I am wanting to modify VALUE in a nice, easy way.
Where I can say Variant2(inner) => *inner += 123 instead of Variant2(inner) => *VALUE.write() = Variant2(inner + 123)
and have to explicitly call VALUE.write() and fully set it or pattern match to modify parts of it.

I have also thought about making the entire thing async, but that seems to be even worse because then the write lock would persist until do_something is completed.

Thanks for the help!

jagged moss
#

That code looks good

#

You shouldn't hold the read/write lock across an await point like this:

spawn(async move {
    let mut value = VALUE.write();
    let new_value = do_something().await;
    *value = new_value;
})
#

spawn runs on the same thread, it isn't multithreaded so you don't need to worry about syncness

#

You can't create UB with signals without unsafe if it was another thread. Dioxus would just panic instead

jagged moss
# jagged moss You shouldn't hold the read/write lock across an await point like this: ```rust ...

Clippy has a nice lint for this for built in locks. If you are using a recent version of the template you might get warnings about this. If not you can copy this configuration: https://github.com/DioxusLabs/dioxus-template/blob/v0.6/Jumpstart/clippy.toml

GitHub

a template for starting a dioxus project to be used with dioxus-cli - DioxusLabs/dioxus-template