The mutual exclusion is very similar to the critical region and is far more complex than the critical region. Because mutual exclusion not only enables the secure sharing of resources within different threads of the same application, but also enables secure sharing of resources between threads of different applications. Through CMutex to complete the coprime between threads, namely: CMutex Mutext;
So we can define data objects like this:
#include "afxmt.h"
class CDataArray
{
private:
int iArray[10];
CMutex Mutex;
public:
CDataArray(){};
~CDataArray(){};
void SetData(int iValue);
void GetDataArray(int aArray[10]);
};
The member functions are implemented as follows:
void CDataArray::SetData(int iValue)
{
CSingleLock SingleLock(&Mutex);
SingleLock.Lock();
for (int i=0;i<10;i++)
iArray[i]=iValue;
}
void CDataArray::GetDataArray(int aArray[10])
{
CSingleLock SingleLock(&Mutex);
SingleLock.Lock();
for (int i=0;i<10;i++)
aArray[i]=iArray[i];
}
In order to access a mutex, it is important to establish a CSingleLock or CMultiLock object for access control. If the mutex is not consumed by the thread, the current calling thread can become a mutex occupier. To achieve access to mutexes, you invoke the CSingleLock member function lock (), which is:
Singlelock.lock ();
If a thread occupies a mutex, the system suspends the current calling thread until the mutex is freed, at which point the suspended thread wakes up and gets control of the mutex.
The release of the mutex is achieved by invoking the CSingleLock member function unlock (). Cdataarray member functions are automatically unlocked when they exit. Because CSingleLock is created on the vertebral stack, the system automatically completes the call to unlock ().
This article is that I am in the learning multitasking multithreading process notes, for everyone to refer to, hope to get you advice.
This article supporting source code