Synchronous asynchronous and blocking 5-asynchronous non-blocking, synchronous asynchronous blocking 5-
For project introduction and code, see synchronous asynchronous and blocking 2-Test small projects.
1. Implementation
1> asynchronous thread IO Processing
unsigned CAsyncIO::ThreadWork(){ int nRet = IO(); //map is better than array at here, but it need STL unsigned uTid = GetCurrentThreadId(); for (int i = 0; i < sizeof(m_uThreadArray) / sizeof(m_uThreadArray[0]); i++) { //Because handle is not same at different thread, so it need use tid to associate the thread and IO caller. if (uTid == m_uThreadArray[i]) { NotifyProgress(100, i); NotifyResult(nRet, i); } } return nRet;}
After the thread calls the IO, it directly notifies the UI result.
2> OnStart ()
bool CAsyncIO::OnStart(){ OnStop(); for (int i = 0; i < sizeof(m_uThreadArray) / sizeof(m_uThreadArray[0]); i++) { HANDLE hThread = StartThread(); m_hThreadHandleArray[i] = hThread; m_uThreadArray[i] = ::GetThreadId(hThread); } return true;}
OnStart () can be returned as long as the thread starts to process IO, so that the main UI thread will not be blocked, and the "Start" button will change to "Stop" after the return ".
3> Implementation of Stop
Since I/O no longer blocks the main thread, the "Stop" button becomes available, and the implementation of Stop becomes meaningful.
bool CAsyncIO::OnStop(){ for (int i = 0; i < sizeof(m_hThreadHandleArray) / sizeof(m_hThreadHandleArray[0]); i++) { HANDLE hThread = m_hThreadHandleArray[i]; if (hThread) { TerminateThreadUntilExit(hThread); ::CloseHandle(hThread); m_hThreadHandleArray[i] = NULL; } } return true;}
Here, the implementation of Stop () is simply to Terminate the thread. Because the thread is terminated directly, it cannot know the status of the thread. what may happen cannot be predicted, and sometimes there may be an inexplicable problem, it is not recommended by Microsoft and should be used with caution.
2. Test
After you click the Start button, although I/O has not been processed, the button immediately becomes available and the UI window can be moved at will.
The asynchronous non-blocking mode does not block the main UI thread, so the user experience is the best. At the same time, it is relatively simple in non-blocking synchronous mode for concurrent processing. Of course, because the main UI thread needs to be notified through callback after IO processing is completed, this will inevitably involve thread synchronization issues, thread Synchronization is a headache. The advantages of asynchronous mode are far greater than that of synchronous mode.