Using threads to execute code within a specified time interval

Knowledge Base Article # Q200095

Read Prior Article Read Next Article
Summary Creating a thread and using the sleep function to execute code at a specified time interval.
You can create a thread to execute code at a specified time interval. This can be useful if you want to take a measurement or reading for example every 200 millisecond. Use the following two part process:

1. Create a thread procedure that accepts one parameter and contains the code you want to repeat on a regular, timed, basis.

The following thread procedure takes 50 measurements. Each measurement takes 200 mSec. Once the measurement is taken, the thread is suspended for the remaining time (of the 200mSec) using the Sleep function, releasing the CPU to handle other tasks:

Procedure MeasurementThreadProcedure(num) : Void
    num: Long
    dwTimeStart : DWord
    dwTimeEnd : DWord
    i : Long

    ! take 50 measurements each should take no more than 200 mSec
    for i=0 to 49
        !Record time before measurement
        dwTimeStart = Tick()
        !Make measurement
        DMM Measure (g_adMeasurement[i])
        !Record time after measurement
        dwTimeEnd = Tick()
        !Let thread sleep for the remaining time of this 200ms time cycle

2. In your main program, you create the thread (in this case supended), start it, and then wait for the thread to end before continuing the main program.

- Create a variable of type AHandle in your variables submodule.

- Instantiate a thread object and link it to the previously created procedure using the following code:

hMeasurementThread = CreateThread(MeasurementThreadProc, 1, True, )

This line of code will create a thread and wait for you to start it with the Resume method.
In this example, MeasureThreadProc is the name of the procedure created in step 1 and MeasurementThreadHandle is the name of the AHandle variable created earlier.

- Optionaly. Set the priority of the thread to time critical for improved timing accuracy.

SetThreadPriority(hMeasurementThread, aPriorityTimeCritical)

- Start the thread by calling its ResumeThread function:


- Use the WaitForSingleObject procedure to wait for the thread to finish execution (with a 20 second time out) before finishing your main ATEasy program.

WaitForSingleObject(hMeasurementThread, 20000)

Article Date 6/17/2008 12:29:33 PM
Keywords ATEasy, Threads, CreateThread, ResumeThread, SetThreadPriority, WaitForSingleObject

0 ratings | 0 out of 5
Read Prior Article Read Next Article