The object of the class ccriticalsection represents a "critical section", which is an object for synchronization. At the same time, only one thread is allowed to access resources or code zones. The critical section is useful when only one thread changes data or other control resources at a time. For example, adding a node to the linked list only allows one thread to run at a time. You can achieve this by using the ccriticalsection object to control the linked list. It is like a key. When a thread obtains it, it obtains the power of the execution thread and blocks all other threads.
The following is a prototype of the constructor of the ccriticalsection class:
Ccriticalsection ()
It can be found that the constructor of this class does not have the number of workers. Therefore, it is easy to create an object of the ccriticalsection class. You can just use the following for example:
Ccriticalsection criticalsection;
Demo: Use a critical segment to compile an application with two threads.
1. Create a single-document application;
2. Define a critical segment object in the View class implementation file:
Ccriticalsection criticalsection;
3. Define two thread functions in the View class implementation file:
Uint messagethread1 (lpvoid pparam)
{
Criticalsection. Lock ();
Lptstr pmessage = _ T ("thread1 is started ");
Cwnd * pmainwnd = afxgetmainwnd ();
: MessageBox (pmainwnd-> m_hwnd, pmessage, _ T ("thread message"), mb_ OK );
Criticalsection. Unlock ();
Return 0;
}
Uint messagethread2 (lpvoid pparam)
{
Criticalsection. Lock ();
Lptstr pmessage = _ T ("thread2 is started ");
Cwnd * pmainwnd = afxgetmainwnd ();
: MessageBox (pmainwnd-> m_hwnd, pmessage, _ T ("thread message"), mb_ OK );
Criticalsection. Unlock ();
Return 0;
}
4. Write the message function with the left mouse button in the view, for example:
Void cthreadtestview: onlbuttondown (uint nflags, cpoint point)
{
Afxbeginthread (messagethread1, _ T ("thread is started"); // start thread 1
Afxbeginthread (messagethread2, _ T ("thread is started"); // start thread 2
Cview: onlbuttondown (nflags, point );
}
The execution result is as follows:
Exam materials:
1. critical section class (ccriticalsection) -- MFC http://blog.sina.com.cn/s/blog_627ebfc30100itd9.html
2. MFC Windows Application Design (version 2nd)