Multi-thread Summary of MFC and multi-thread Summary of mfc
The CPU scheduling unit is the thread rather than the process. The scheduler data is sorted by the priority of each thread. If thread A and thread B have the same priority, the scheduler selects the one that has been waiting for A long time.
I. Thread Scheduling
The scheduler will elastically adjust the thread priority to strengthen the system's response capability and avoid any thread from being able to accept CPU polishing. For example, the general thread priority is 7. If it is switched to the foreground, the scheduling system may temporarily raise it to 8 or 9 or higher. The scheduling system temporarily increases the priority of threads with input messages waiting for processing.
Ii. Thread generation
With: CreateThread, a thread is generated and a thread function is specified. It is a worker thread. Unless it is exposed to input messages in its life, there should be a message loop, to capture the message, the thread becomes the UI thread.
The CWinThread object represents a thread. Whenever you need a thread, you should not directly call: CreateThread or _ beginthreadex In the MFC program. You should first generate a CWinThread object and then call its member function CreateThread or the global function AfxBeginThread. CWinThread: CreateThread or AfxBeginThread internally calls beginthreadex.
CWinThread: CreateThread and AfxBeginThread not only encapsulate: CreateThread, but also initialize internal data required by the application framework and ensure that the correct C runtime library version is used.
1. Generate a Worker Thread
CWinThread *pThread = AfxBeginThread(ThreadFunc, ¶m);UINT ThreadFunc(LPVOID param){}
2. Generate a UI Thread
UI Thread cannot be represented by a function. You should first derive a class from CWinThread, and then call AfxBeginThread to generate a CWinThread object.
Note:
(1) The thread function is called by the system, that is, a callback function. this pointer parameter is not allowed. Therefore, no general C ++ class member function can be used as a thread function. It must be a global function or a static member function of the C ++ class.
(2) It is better to focus all UI operations on the main Thread, and other "Pure operation operations" will be considered for Worker Thread.
Iii. End of Thread
The life of a Worker Thread is the Thread function itself. Once a function is returned, the Thread ends. Or the thread function calls AfxEndThread to end a thread. Because the UI Thread has a message loop, you must put a WM_QUIT in the message queue to end the Thread. Or calling AfxEndThread in any function of the thread can also end the thread.
AfxEndThread calls _ endthreadex internally and ends the thread.
4. Thread and Synchronization Control
Windows provides four synchronization mechanisms, and MFC also provides four corresponding classes.
(1) Critical Section (key areas ).
(2) Semaphore (Semaphore ).
(3) Event ).
(4) Mutex (Mutex ).