Andreas Reiff
Andreas Reiff

Reputation: 8404

Synchronisation object to lock in one thread and release in another

I have a case where I want to acquire (lock) a resource in a function call, but am signaled of the end of the process in a callback (different thread). (The resource is external: basically, a certain bus gets busy when I start and is free again with the callback.)

With lock/critical section this is not possible at all. I also tried Mutex, but only get exceptions, probably because I release in another thread.

What are the options here?

It seems that I can

  1. create bool to "manually" sync them (lock access to volatile bool, and then do a while() sleep instead of the WaitOne)
  2. use events to single-thread the whole thing in a 3rd wrapper thread that then also manages the synchronization object

I would probably go for the bool though for simplicity. Or preferably any mechanism provided by the runtime. The callback comes from an external library.

Update: I have also just now discovered the semaphore, which seems to fit my needs. I will ask anyone in case someone has a better idea/someone else finds this useful, too.

Upvotes: 1

Views: 349

Answers (1)

ken2k
ken2k

Reputation: 48985

A simple way to solve your problem is to use an AutoResetEvent: you wait for it in a thread, and notify to release the lock in the other thread.

Upvotes: 2

Related Questions