Click here to Skip to main content
15,894,539 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

Could you please explain me the difference between a Mutex and a Single ton with a small example.

My understanding is we can create only one instance(object) of a class in singleton class.

And in Mutex is useful to have locking control over an object in two different process.

Please let me know in detail with a small example in C++ for Mutex and singleton.

I want to have only one instance of application running at any time .

Appreciate your help.

Thanks,
Sudhakar
Posted
Updated 24-Mar-14 0:55am
v2

Both things have nothing to do with each other.

A singleton is a design pattern that is used whenever you want to guarantee that only one object of a class exists. Example: A class that manages all devices in your system and which assumes that only one such manager may exist within your program. Singletons are considered within the context of a process, i.e. only one object of the class may be created within a process. And hence, a singleton cannot be used for the purpose you described.

A mutex is a system object that can be used to regulate that access to a resource by multiple processes or threads. Example: Multiple processes might us a mutex to coordinate their access to a shared file. A mutex can be accessed by multiple processes to do this kind of coordination. It is the usual tool that is utilized for the purpose you describe.
 
Share this answer
 
 
Share this answer
 
Comments
Member 3975629 24-Mar-14 9:31am    
Thanks for the link on mutex. but how singleton is different from Mutex. I mean functionality wise singleton also allows only one instance of the class.

Thanks,
Sudhakar
Mehdi Gholam 24-Mar-14 9:37am    
The link above gives a good analogy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900