Creation of Windows core programming can wait for timers and their APC callbacks

Source: Internet
Author: User
Tags apc filetime

Overview

Creating a waiting timer is one of the ways that Windows internal thread synchronization works, and this article simply describes how to use this kernel object for thread synchronization.

How to useTo create an object:

Create event kernel object, default not triggered state handle htimer = CreateWaitableTimer (null, TRUE, NULL);

To set object properties:

CreateWaitableTimer the kernel object is not triggered when the creation is complete, you need to use Apibool WINAPI setwaitabletimer (__in          HANDLE htimer,__in          const large_integer* pduetime,__in          LONG lperiod,__in          ptimerapcroutine pfncompletionroutine,__in          LPVOID lpargtocompletionroutine,__in          BOOL Fresume); To set some properties of the timer object, Pduetime is the first trigger time (UTC time), Lperiod indicates the frequency at which the timer should be triggered after the first trigger.

using APC callbacks to handle timer object trigger events: (APC, asynchronous procedure call, asynchronous program invocation )

void CALLBACK TimerCallback (LPVOID Lpargtocompletionroutine, DWORD Dwtimerlowvalue, DWORD Dwtimerhighvalue) {// Here processing timer triggers int i = 0; SetEvent (g_hhelpevent);//do something}


Voidwaitabletimertest () {///Create Event kernel object, default does not trigger state handle htimer = CreateWaitableTimer (null, TRUE, NULL);//create event, set to not trigger state g_ Hhelpevent = CreateEvent (null, TRUE, FALSE, NULL); SYSTEMTIME St; Getlocaltime (&st);//st.wsecond + = 40; FILETIME ft; SystemTimeToFileTime (&st, &ft);//convert to UTC time FILETIME FTUTC; LocalFileTimeToFileTime (&ft, &AMP;FTUTC); Large_integer ftime;ftime.lowpart= ftutc.dwlowdatetime;ftime.highpart= ftutc.dwhighdatetime;//a minute after the current time is triggered, the bool BRet = SetWaitableTimer (Htimer, &ftime, 10*1000, TimerCallback, (LPVOID) Htimer, FALSE) is triggered every 10 seconds;D word dwerror = GetLastError ();//After the TimerCallback callback is added to the system APC queue, only through SleepEx, WaitForSingleObjectEx, Waitformultipobjectex,/ /or signalobjectandwait into the wait state the APC callback function can be called by the same thread. while (wait_timeout = = WaitForSingleObjectEx (g_hhelpevent, N, FALSE)) SleepEx (1000*60, TRUE); switch (dwret) {case wait_object_0://cout<< "Timer object has been triggered" <<endl;break;case wait_timeout:cout<< "Wait timeout, auto stop timer object" < <endl; Cancelwaitabletimer (Htimer); Break;case wait_failed:cout<< "WaitForSingleObject call failed with system error code:%u" <<getlasterror () <<endl;break;} CloseHandle (Htimer); CloseHandle (g_hhelpevent);}


how to guarantee the trigger, the key is:

After the TimerCallback callback is added to the system APC queue, it can be used only through SleepEx, WaitForSingleObjectEx, Waitformultipobjectex,
Or signalobjectandwait into the wait state, the APC callback function can be called by the same thread. This means that only these APIs can be used to block the current thread, and the APC callback function will be called by the rerouting thread.
If the argument is false, the function does not return until the time-out has expired. If an I/O callback function appears, the function will not return and the callback function will not execute. If an APC function is inserted into a thread, the function does not return and the APC function does not execute. </span>
If the argument is true and SleepEx is in the same thread as the extended I/O function (ReadFileEx or WriteFileEx), the function returns immediately when the thread hibernation timeout or the I/O callback function appears. If the I/O callback function appears, then the I/O callback function is called. If an APC is inserted into a thread, the function executes immediately regardless of whether the current thread timed out, and the APC function is called.


One of the pitfalls of Windows kernel programming:

BOOL BRet = SetWaitableTimer (Htimer, &ftime, 10*1000, TimerCallback, (LPVOID) Htimer, FALSE);
WaitForSingleObjectEx (Htimer, INFINITE, TRUE);
This should not be done because WaitForSingleObjectEx actually waits two times, one is a reminder, and the other is the kernel object handle. When the timer is triggered, the wait succeeds, the thread is awakened, the thread exits the alert state, and the APC function is not called.


The difference between a waiting timer and a Windows timer message:

1, timer messages need to use a large number of user interface infrastructure in the application, thus consuming more resources; The wait timer is a kernel object that can be shared not only among multiple threads, but also with security.

2, the timer message can only be targeted at one thread, the message loop is in the thread unit, while the waiting timer can change the scheduling state of multiple threads.

3, Wim_timer message is always the lowest priority, only the thread in the message queue no other messages will be processed. The wait timer is no different from other kernel objects, and the system wakes up the thread if the timer is triggered and the thread is waiting.

At last:

It is important to note that the APC callback must be processed as soon as possible to avoid a callback that has not yet been processed to complete another callback.


Creation of Windows core programming can wait for timers and their APC callbacks

Related Article

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.