0

Does sem_wait/sem_post work the same as pthread_mutex_lock/unlock?

If it doesn't, what major difference they have? For coding wise, I only know that sem_wait() requires initialization which is sem_init() and pthread_mutex doesn't require it. But other than that I don't really know what is the best situation to use semaphore / mutex.

Also, If I have multiple shared data between different threads function, should I use multiple locks? For example,

If I have

linkedlist sharedtype1;
linkedlist sharedtype2;

Whenever I perform read or write on thread function on sharetype1 I use mutex1 and for sharedtype2 I use mutex2. Or should I use single mutex/semaphore?

  • https://afteracademy.com/blog/difference-between-mutex-and-semaphore-in-operating-system – Sandeep Jadhav Dec 02 '21 at 05:56
  • https://stackoverflow.com/questions/2065747/pthreads-mutex-vs-semaphore – Sandeep Jadhav Dec 02 '21 at 05:58
  • 2
    A pthread mutex does require initialization. It could be a static one though. – Cheatah Dec 02 '21 at 05:59
  • "If I have multiple shared data between different threads function, should I use multiple locks?" There's no one-size-fits-all answer for this, completely depends on your situation. You can have a lock for every single bit of a field if you wanted. You can have one lock to rule them all [(the linux kernel used to)](https://en.wikipedia.org/wiki/Giant_lock). The sweet spot is probably somewhere in the middle. You'd have to code it up certain ways and do some profiling if you really wanted to see what is best in your case, altho some educated guesses can certainly be made. – yano Dec 02 '21 at 06:30

0 Answers0