I was looking at this post
And RawMutex was suggested.
I would like to use it for a function in my program.
I was hoping to do something like this:
So only one thread hits it.
raw_mutex.try_lock()
a().await;
raw_mutex.unlock() // not sure how to release lock
or
async fn a(){
raw_mutex.try_lock()
}
I'm using try_lock, so if another thread does call this function, it will skip it, which is the desired behaviour.
I tried this looking at at parkinglot doc
let m: RawMutex = RawMutex::INIT;
But getting errors everywhere.
H2CO3
October 14, 2022, 7:56am
2
There absolutely is an unlock()
function on RawMutex
, and declaring a variable an initializing with that constant is correct, too. It would be helpful to state what code exactly you tried and what specific errors you are getting.
Ok,
So the first error was that I needed to add dyn. Fortunately, Rust Analyzer fixed that.
let m: dyn RawMutex = RawMutex::INIT;
Now the error is :
the trait parking_lot::lock_api::RawMutex
cannot be made into an object
parking_lot::lock_api::RawMutex
cannot be made into an objectrustcE0038
the value of the associated type GuardMarker
(from trait parking_lot::lock_api::RawMutex
) must be specifiedrustcE0191
main.rs(29, 16): specify the associated type: RawMutex<GuardMarker = Type>
OK, I read the error message, and the link to E0191. But not sure how to use it.
H2CO3
October 14, 2022, 8:15am
4
No, you don't. dyn Trait
is a dynamically-sized type which means that you can't pass it around by-value. You are probably confusing the RawMutex
trait with the RawMutex
type. You should be able to create a raw mutex by writing
let m: RawMutex = RawMutex::INIT;
where RawMutex
-the-type is in scope, and not the trait.
H2CO3:
let m: dyn RawMutex
Is this a typo or intentional?
H2CO3
October 14, 2022, 8:36am
6
A typo, of course – thanks!
Yes, thank you.
Worked using a qualified namespace.
But using imports just wasn't working. Rust analyzer kept picking up the trait.
let m: parking_lot::RawMutex = parking_lot::lock_api::RawMutex::INIT;
m.try_lock();
println!("ok");
unsafe { m.unlock() };
Interesting that I needed to use unsafe block
H2CO3
October 14, 2022, 8:56am
8
It should (proof ). Rust-analyzer is not the compiler, and its output is not normative.
system
Closed
January 12, 2023, 8:56am
9
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.