Reputation: 3287
I have the following code:
int resource;
sem_t s;
void function2()
{
// do some operation to resource
}
void function1()
{
sem_wait(&s);
function2();
sem_post(&s);
}
if we have different process call the function1
simultaneously, and function1
is already protected by semaphore, do we need to have semaphore to protect function2
?
Upvotes: 0
Views: 175
Reputation: 727
As @VoidPointer said on the comment, not needed IF the function2 is not called anywhere else but inside the function1.
Thats easy to see why: you could think the function2 to be inlined where the call is, right? Well between the sem_wait and sem_post is always only one process -- so your data is safe.
But as @rakib said, its better to lock data only when needed to avoid unnecessary waiting.
Are you sure that you want to use semaphores and not mutexes? See for example: Difference between binary semaphore and mutex
Upvotes: 0
Reputation: 142825
What you really need to do, is to protect your share data using semaphore. Atleast this is the best practice. Semaphore is basically use to protect data, which is accessible from various functions. A typical use might look like this:
struct data {
yoursharedata;
sem_t lock;
}
Whenever you'll access to yoursharedata (from any function) grab the lock, manipulate the data and release the lock. Something like below:
sem_wait(lock);
pock(yoursharedata);
sem_post(lock);
Hope this will help!
Upvotes: 1
Reputation: 4002
From your code i can say that you protected Function call(function2()) inside function1, not function1. Any calls refer function1 will wait until it returns from function2 and I think no need to protect function 2 again unless you have shared resource inside function 2. If you have shared resources inside function 2 you need to protect that resources.
Upvotes: 0