initializationsemaphore

What happens if you try to initialize a semaphore to a negative value


What happens if you try to initialize a semaphore to a negative value

for example

semaphore s = -1;

I know that it does not make sense, but I want to know if you do that, will get error messages and your program won't execute; or there will be no error messages and you will face logical errors later.


Solution

  • As you've said, it wouldn't make sense, as binary semaphores are supposed to only take the values 0 and 1, while counting semaphores are supposed to only take non-negative integer values. However, to answer your question, I would assume that the reaction of the program to a semaphore initialized to a negative value would depend on the programming language.

    I gave it a try with C# and I can say that

    private static Semaphore _pool = new Semaphore(-1, 3);
    

    returns

    System.ArgumentOutOfRangeException: 'Non-negative number required. Parameter name: initialCount'