I did not really understand suspendthread functions. When I recently used multithreading to execute tasks, I found that sometimes it is more convenient to use it than to use additional kernel objects.
DWORD WINAPI ThreadProc( PVOID pvParament ){int iCnt = 0;while ( 1 ){cout<<iCnt<<endl;if ( iCnt > 10000 ){break;}++iCnt;}return 0;}void main(){bool bExit = FALSE;HANDLE hThread = CreateThread( NULL,0,ThreadProc,NULL,0,NULL );Sleep( 2000 );SuspendThread( hThread );Sleep( 2000 );ResumeThread( hThread );WaitForSingleObject( hThread,INFINITE );CloseHandle( hThread );}
Here, the two functions are used to complete the thread running-interrupt-continue state switching.
In core programming, we have made some guidance on how to completely terminate the thread: let us try to implement the thread to exit, rather than using the Windows forced functions.
The Code roughly means:
DWORD winapi threadproc (pvoid pvparament) {While (waitforsingleobject (hevent, infinite) = wait_object_0) {// perform operations cyclically. Save the current status in the loop.} return 0 ;}
In this way, we can use hevent to control the thread pause, continue, and exit. In general
The main problems with this writing method are:
1. the entire thread execution body is inside while, but the initialization Code cannot be placed in while. The current solution may add the initialization code to the front of while. The only problem is that the initialization code status cannot be controlled.
2. when the thread is under control, it cannot reach the "pause" object, because we need to manually Save the current State until the hevent changes to the trigger state, continue (the entire process is completely controlled by ourselves). In fact, we can use suspendthread.