Programming with Hyper-Threading Technology: How to Write Multithreaded Software for Intel IA-32 Processors

Interlocked Functions

The section on spin waits earlier in this chapter described the problem of having two threads update the same variable. Basically, by accessing the variable simultaneously, two threads might read the variable when it had a value of 8, for instance. They would then both increment it and write it back out. As a result, the new variable would show the value of 9, rather than the correct value of 10. Because counting is such an important part of thread synchronization, Windows developers might be tempted to write small critical sections whose sole action is to increment or decrement a variable.

While this approach will work, Windows provides a highly efficient set of functions to do this very thing. They change the value of a long integer without recourse to critical sections. These routines, known as interlocked functions, are centered on the InterlockedExchangeAdd() function. Here's how it works:

LONG InterlockedExchangeAdd ( &long_num, increment_amt )

The long_num is a previously defined long integer, which must be placed on a 32-bit boundary. The increment_amt variable is a long integer containing the amount by which long_num should be incremented. To decrement long_num, simply use a negative value in increment_amt. The function returns the value of long_num before it was incremented. By using this function, you know that the updates will occur without conflicts between threads, or atomically.

The variable governed by the interlocked functions is any common integer, except for the requirement of...

UNLIMITED FREE ACCESS TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: Parity Checkers and Generators
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.