简体   繁体   中英

Realize hardware lock for multiplexer in C#

We use a physical (de)multiplexer in our system (time division, one input, several outputs).

While one channel is routed, an action is executed (eg doing something on the routed connection). During this action, noone else is allowed to route the multiplexer to another channel.

For this scenario we currently use the lock statement as in

public void DoSomething(Action action, int channel)
{
    lock(_lock)
    {
        _multiplexer.Route(channel);
        action();
    }
}

Is using lock appropriate in this use case or are there other approaches to handle locking a hardware device? I often read

Keep locks tight

and

Never execute arbitrary actions within a lock

Do these rules apply in this situation?

Yes, this is an appropriate use of locks (as opposed to other locking mechanisms). However, some might argue that another cross-process type lock like a named mutex should be used because if multiple processes could be started, they could both access the hardware at the same time, potentially corrupting data.

"Keep locks tight" generally means that you should make sure that you don't do any unnecessary processing while holding the lock. For example, if you need to allocate some space to put data in, that can generally be done outside the lock. The second rule is generally to avoid deadlock. For example, if inside the action passed into DoSomething , the code were to lock a different lock, and in some cases other code were to access that lock before calling DoSomething , if those two code paths happened to run at the same time, you'd have deadlock (one would hold this lock and wait for the other one, and the other would hold the other lock and wait for this one). If the developers using this code have the discipline to never take any locks or do any unnecessary processing in the specified action, things will work fine, but that's a big if.

If it's possible, it would be much safer (better) to code up all the possible operations that can be done on the channel in a way that all the locks are hidden within the implementation and no calls to outside code are made while the lock is held. That way, there is no way someone who doesn't understand the internals could write code that causes deadlock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM