Page 53 - Designing Autonomous Mobile Robots : Inside the Mindo f an Intellegent Machine
P. 53
Chapter 3
Many functions are called infrequently, execute quickly, and release the processor.
However, other threads may execute for substantial periods of time as they act on
large amounts of data or loop waiting for a condition to occur. These tasks must
release the processor (CPU) periodically. In VB this is done by including a function
call to DoEvents.
DoEvents is an operating system call that relinquishes control of the CPU to the
operating system so that it can determine if an action event has occurred. If an
event has occurred, it will be serviced and then the CPU will return to continue
servicing the original thread.
For example, the operating system might find that a hardware timer has timed out
and thus execute a function associated with that timer. Under VB, individual timers
are not implemented with hardware counters as they are on many microcontrollers. Instead,
they are more like the settings of an alarm clock against which a master clock is compared.
Therefore, a timer does not time out and cause an action, but rather the operating system
calculating that the timer has timed out causes the action event. This important distinc-
tion has both an advantage and a disadvantage.
Since the operating system must gain control of the CPU in order to execute any
event, threads are in no danger of being blindsided by an interrupt and losing con-
trol of the CPU involuntarily. Instead threads must complete and release the CPU,
or they must intentionally relinquish control temporarily by executing a DoEvents
function call. This important distinction makes writing well-behaved tasks much
simpler under VB. This is akin to masking off interrupts, or more accurately only
enabling interrupts at specific points.
Unfortunately, like training wheels on a bicycle, this protection comes at a price.
The price is that no timer or other software event will be serviced instantly, but it
will instead be recognized and executed the next time some polite running thread
releases control of the CPU.
The longest period between when the event actually occurs and when it is serviced,
is called its latency. If threads are written with very large blocks of code that are not
broken up by DoEvents calls, then the latency can be as long as the time required for
the largest of these blocks to execute. This means that timer-driven tasks under VB
are not very precise, especially if other threads are doing time-consuming tasks such
as graphics. Even so, with CPU speeds of several GHz, the latency may not be very
severe.
36

