What if we keep calling semGive multiple times without semTake in binary semaphore? What will be the behavior?

57 views Asked by At

We have created a binary semaphore with semBcreate.

Code fragments:

semTake(with 10s wait); // it will be called only once during restart
semGive();              //this will be called from multiple thread. 

so here we will have lots of semGive() called without any semTake(). As it was called only once during reboot of device to achieve synchronization.

Please help me answering this, we don't see any problem but what if device will run for long time and there will be lots of semGive called in binary semaphore?

We tried calling semGive many times, couldn't notice any potential issue. But we need to understand if there is any cons of doing this way.

1

There are 1 answers

1
Solomon Slow On

We tried calling semGive many times, couldn't notice any potential issue

That is almost always a Bad Idea. You should go with what the documentation says. If the documentation does not guarantee that the semaphore (or any other thing) always will behave in the way that your program needs it to behave, then you are setting yourself up for future trouble.

What happens if some library developer decides that the current implementation is buggy,* and they fix the bug? The bug fix goes out as part of an OS update, your customers accept the update, and suddenly your application stops working for everybody, everywhere, all at once.

Been there. Done that. It wasn't fun.

I've never heard of this semBCreate. But @teapot418 found a page that might be for the same semBCreate that you are using. It seems to me as if maybe you can infer that multiple calls to semGive(s) with no semTake(s,...) in between will have the same effect as a single call to semGive(s). If that's the behavior that your program requires, then you probably are OK.

On the other hand, the doc does not explicitly talk about that case,** so maybe you should shoot an email to the library authors just to be sure.


* The documentation for the C++ standard libary's binary semaphore pretty much guarantees that it will not behave the way your program expects a binary semaphore to behave.

** What you're doing is not the normal use-case for a binary semaphore.