1
votes

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.

1
Can you be very specific about what you want to do? I suspect what you want can be done with Monitor.Wait and Monitor.Pulse / Monitor.PulseAllMarc Gravell
@Marc I want to synchronize several threads requesting my operation at the same time. My problem is that the operation takes from when I start the request to when my callback is called. From looking at Monitor in MSDN, I could not call enter and leave in 2 different threads. To use Pulse I would have to write logic that manages the access to the resource myself.Andreas Reiff
@AndreasReiff sounds like you want a semaphore, thenMarc Gravell

1 Answers

2
votes

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.