18.2.3 Re-entrance Requirement

A procedure may be called by any number of different programs concurrently. That is, program A may call a DLL procedure while program B is still executing the same procedure. The basic problem of re-entrance is how data is shared.

Summary: Be aware that re-entering the DLL can modify its data.

For example, suppose you have a DLL that contains an accounting package; one of the functions adds up an employee's salary for a whole year. First it initializes the total to zero; then it increments this total one week at a time. While program A is in the middle of this function, program B could enter the procedure; its first action would be to initialize the total to zero. Control could then pass back to program A, which would then have zero total for salary. The problem is that two instances of the DLL share the same variable for totals.

A procedure in a DLL must therefore follow this rule: it can access static data items but must not alter them. Otherwise, one instance of a procedure could corrupt data relied on by another instance of the procedure.

There are several exceptions to this rule. First, if data is declared NONSHARED in the module-definitions file, each instance has its own copy of the data segment, and there is no conflict. Second, you can use semaphores to allow mutually exclusive access to data items. Finally, there may be some items you deliberately want all instances to alter—such as a global counter to keep track of number of instances.

Section 18.4.1, “Writing the Module-Definition File,” explains how to declare some data items as SHARED while declaring others to be NONSHARED.