Timing a Single Interval

To carry out other tasks while the timer counts an interval, an application can use DosAsyncTimer. This function sets a single-interval timer without stopping the application-the timer runs asynchronously to the calling thread, enabling the thread to perform other operations while it is waiting for the specified time interval to expire. When the interval elapses, OS/2 notifies the application of the expiration of the timer by posting an event semaphore. The application resets the semaphore before starting the timer and monitors the semaphore to determine when the time has elapsed. The application can use DosCreateEventSem with the initial state FALSE to create a reset semaphore. For more information on semaphores, see Semaphores.

The following code fragment creates an event semaphore and then calls DosAsyncTimer to count an interval while the application performs other tasks:

    #define INCL_DOSDATETIME    /* Date/Time and Timer Support */
    #define INCL_DOSSEMAPHORES  /* for semaphores              */

    #include <os2.h>

    HEV hev;
    HTIMER hTimer;

    /* First create a private, reset, event semaphore. */

    DosCreateEventSem((PSZ) NULL,
                      &hev,
                      DC_SEM_SHARED,
                      FALSE);

    /* Start async (one-shot) timer; post semaphore in 10 seconds.  */

    DosAsyncTimer(10000,       /* Time in milliseconds (10 sec)     */
                  (HSEM) hev,  /* Semaphore handle                  */
                  &hTimer);    /* Timer handle (used to stop timer) */

        .
        .    /* Do other processing here, then wait for semaphore.  */
        .

    DosWaitEventSem(hev,
                    SEM_INDEFINITE_WAIT);

Before starting the timer, the thread creates the event semaphore with DosCreateEventSem, specifying its initial state as reset. If the semaphore was previously created by the same process, the thread resets it by calling DosResetEventSem. If the semaphore was previously created by another process, then the thread must call DosOpenEventSem to gain access to the semaphore before calling DosResetEventSem.

Next, the thread calls DosAsyncTimer, specifying the handle of the event semaphore and the desired time interval. The thread can then perform other tasks. However, in order for the application to be notified of the expiration of the timer, one or more threads in the application must call DosWaitEventSem.

When the time interval expires, the system posts the semaphore, and any threads that were blocked on DosWaitEventSem requests can resume their execution. If another time interval is required, the semaphore is reset, and both DosAsyncTimer and DosWaitEventSem are called again. (To time regular repeated intervals, use DosStartTimer.)

The timer can be canceled before its time interval expires by calling DosStopTimer.


[Back: Suspending the Current Thread]
[Next: Timing Repeated Intervals]