Using Mutexes

来源:互联网 发布:美工常用设计字体打包 编辑:程序博客网 时间:2024/06/05 19:45

Using Mutexes

Mutexes provide serialised access to shared resources. They areKernel objects and, as such, are managed by the Kernel.

A mutex can be used by threads across any number of processes. If aresource is only shared between the threads within the same process, it can bemore efficient to use a critical section.

Access to a mutex is through an RMutex handle.

Mutexes are similar to semaphores in that they have aTInt count value that is incremented by calling theSignal() member function of the mutex handle and decremented bycalling the Wait() member function of the mutex handle. A mutexwith a negative value implies that a thread must wait for access to the sharedresource.

Unlike a semaphore, the count value of a mutex is always set to onewhen it is constructed.

The creator of a shared resource uses the CreateLocal()or CreateGlobal() member functions of RMutex tocreate a mutex and to open the handle to it. Any thread wishing to access theresource first calls Wait(); that thread then callsSignal() after completing its access.

The first thread to call Wait() returns immediately, andis free to continue execution, but any other threads that callWait() will wait in a queue maintained by the mutex. Waitingthreads are released on a first-in first-out basis when the thread currentlyaccessing the resource calls Signal().

The nature of the shared resources should be such that any accesscompletes in a relatively short time so that threads do not wait for extensiveperiods on the mutex.

In many cases, it may be better to use servers to serialize access toa shared resource (for example, the window server) rather than use a mutex.

原创粉丝点击