Nikhil Wagh
Nikhil Wagh

Reputation: 1498

Why can't we access semaphore

I was reading about semaphores, and here I found that you can not access (increment/decrement) a semaphore directly.

A Semaphore is an integer variable, which can be accessed only through two operations wait() and signal().

I have two questions regarding the topic:

  1. What is the type of semaphores. Is it a structure or some other datatype.

If it is a structure then my second question is:

  1. Why can't we access the semaphores with semaphore.some_value++.

And if it is a variable which I found on wikipedia :

A trivial semaphore is a plain variable Then why can't we access it like semaphore1++?

I tried to increment it and got this error:

error: wrong type argument to increment

Why is it forbidden from the user, why do we have to use the functions to access it? (Although I agree, that it is not a bad practice to use functions, but Why?)

Upvotes: 1

Views: 1219

Answers (1)

mhsmith
mhsmith

Reputation: 8111

The functionality of a semaphore is not merely in the incrementing and decrementing of an integer, but also in the communication between the semaphore's users. The communication aspect is what is encapsulated by the wait and signal functions. In particular, on most operating systems, they will use lower-level kernel features so that the wait doesn't need to waste CPU repeatedly checking the semaphore's value.

The fact that you received that compiler error shows that, on your system, a semaphore is a structure. However, you would not be able to use the semaphore by accessing the structure members directly, because that would not affect the underlying kernel object.

Upvotes: 1

Related Questions