How to use RawMutex from parkinglot crate, need a sample

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.unlock() // not sure how to release lock 


async fn a(){

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.

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.

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, 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.

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.

Is this a typo or intentional?

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;

  unsafe { m.unlock() };

Interesting that I needed to use unsafe block

It should (proof). Rust-analyzer is not the compiler, and its output is not normative.

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.