Semaphores and Mutex for Thread and Process Synchr

2019-02-16 03:03发布

问题:

I am confused with the usage of semaphores and mutexes at thread and process level. Can we use semphores and mutexes for both thread and process synchronization, or do we have different semaphores and mutexes both at thread and process level? My question is with reference to the POSIX API's.

回答1:

The answer to both questions is yes. You can create both mutexes and semaphores as either process-shared or not. So you can use them as interprocess or interthread synchronization objects, but you have to specify which when you create them.

Of course, you must create the synchronization object in memory that is shared by all contexts that wish to access it. With threads, that's trivial since they share a view of memory. With processes, you have to create the synchronization object in shared memory specifically.



回答2:

Synchronization protects elements when they share data or when their tasks must be ordered.

Processes and threads basically are the same (with differences) they are pieces of computation that make some work, the only thing you have to pay attention is when you are working with processes and when with threads but the method used is the same.