# Where can I find a good tutorial on mutexes?

## Recommended Posts

Sorry to have to bring the question here, but I've searched all over the internet and can't seem to find one. My problem is that I have many instances of a certain classes, that all interact with each other's members. Namely a char*. Problem is, they're all multi-threaded and running individually and I don't want 2 instances editting another at the same time. So, I figured... find a way to freeze everything trying to edit this instance until whatever's already editing it is finished. I'm currently using process.h (with teh _beginthread()) for my multi-threading if that makes any difference. So if at all possible, I'd really appreciate a simple tutorial (possibly) including functions to use (developing for W98SE) and basic theory on mutexes. Thank you very much! --Aternus

##### Share on other sites
a mutex is just an object that is either signaled or unsignaled. in windows you use the function CreateMutex to create a mutex. example:

class Monitor { private :  HANDLE mutex; public :  Monitor()  {   mutex = CreateMutex(NULL, FALSE, NULL); // not signaled  } ~Monitor()  {   CloseHandle(mutex);   mutex = 0;  }};

so now say you want to protect a variable from being accessed at the same time by different threads... check out the function SetValue below...

class Monitor { private :  HANDLE mutex;  int value; // need to protect public :  Monitor()  {   mutex = CreateMutex(NULL, FALSE, NULL); // not signaled  } ~Monitor()  {   CloseHandle(mutex);   mutex = 0;  } public :  void SetValue(int v)  {   // the region between WaitForSingleObject and ReleaseMutex is   // called a critical section as only one thread at a time can   // be there so you don't have to worry about concurrent access   WaitForSingleObject(mutex, INFINITE); // wait for ownership   // mutex is now signaled   value = v; // set value   ReleaseMutex(mutex); // release ownership   // mutex is now unsignaled  }  void GetValue(int& v)  {   WaitForSingleObject(mutex, INFINITE); // wait for ownership   v = value; // read value in critical section   ReleaseMutex(mutex); // release ownership  }};

this is a real simple example of a monitor however... if you have certain conditions that must be met before you can set or read a value you'll need other syncronization objects as well.

##### Share on other sites
Alright. That was a lot simpler than I expected. Thanks!

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627637
• Total Posts
2978336

• 10
• 12
• 22
• 13
• 33