Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Can we write a lock async without unsafe?
Hi! I was thinking to try write some async code for postgres using pgrx, how PG/PGRX request the element to be copy, I'll be using an array in this example.
In async code, everything can be called in any time, but I have some issues with the normal lock functions.
We have a array with a struct, the struct can need change it self:
struct Foo;
impl Foo {
fn read_something(&self) {
todo!()
}
fn change_something(&mut self) {
todo!()
}
}
struct Arr([Option<Foo>; 10]);
impl Arr {
fn try_add_element(&mut self, foo: Foo) -> Result<(), Box<dyn std::error::Error>> {
todo!()
}
fn try_rm_element(&mut self, foo: Foo) -> Result<(), Box<dyn std::error::Error>> {
todo!()
}
fn read_element(&self, id: usize) -> Result<&Foo, Box<dyn std::error::Error>> {
todo!()
}
fn mut_element(&mut self, id: usize) -> Result<&mut Foo, Box<dyn std::error::Error>> {
todo!()
}
}
The basic design is that thing, we have a box that stores Foo, and then we can request different things inside.
I'm writting this as a test, I have never done this and why not use the normal locks?
Imagine, a section already requested Foo1
, now we want to add a new Foo, in normal apps this would request a exclusive access to Arr
, but if we only want to add something we does not need a full exclusive, we only a instance where add a new element is exclusive.
So, while we want to add a new Foo, we should be able to keep working normally with all elements without block everything for that operation, obvs if we want to remove we should request a complete exclusive access.
Split the read, add and remove elements in Arr allow to most inside elements keep working without lock everything every single time.
The issue? I can't found how to design this without unsafe code... when I go and look on other crates and lib, is like internally all with unsafe code, so I was asking myself if there is a way to develop async mechanism without unsafe code! maybe this always needed them, mutex seems to also uses unsafe code.
I'm giving a lot of context, to just to avoid misunderstandings
As other notes, I have read but I still do not get very well how the traits Sync and Send works not how interacts across threads, I also tried to look if there was a simple of example for example for a Mutex but I could not find.
2 posts - 2 participants
🏷️ rust_feed