Thread status switch exit-pause-continue

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.