Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 565
  • Last Modified:

What's Mutex?

I got a program (MSVC) from someone else. There is a function called CreateMutex() in it which generate a mutex object. What's call Mutex? Why we use this function?
0
chenwei
Asked:
chenwei
1 Solution
 
rondiCommented:
A Mutex is a special area of memory managed by the
Operating System (Windows).

It is used for inter-process synchronization.

If two processes (programs) need to access and modify
shared memory (eg. global variables), it is important that one waits for the other, or else the memory may be corrupt/invalid.

The first process will call CreateMutex() to initialize the
Mutex Object (not the memory per se) with a given name.

The second program will call either OpenMutex() or CreateMutex() to get a handle to the Mutex Object with the
same name.

When one of the processes needs to access the shared memory, it calls WaitForSingleObject() with the mutex handle and the max waiting period as parameters.

When it's finished with the memory, it calls
ReleaseMutex(). At this point, the next waiting process can
get ownership of the mutex.

Example use of a Mutex:
-----------------------
Since mutexes are system-wide, a program can use a mutex
to make sure that it only runs 1 instance at a time.
When the program starts it tries to CreateMutex() using
it's name (eg. 'progx_exe'). If it succeeds, then it runs
as usual.
If it fails then it assumes there's another copy
of the program already running and exits before any damage
is done (without trying to delete the mutex). The first program will delete it's mutex when it exits.
0
 
chenweiAuthor Commented:
Thank you.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now