When a serialized procedure does not provide sufficient protection

If you have a global all-thread static variable, it may seem like a good idea to control access to it by having serialized "get" and "set" procedures for the variable. Unfortunately, this does not give adequate protection, because the procedures are serialized independently, each having its own separate control mechanism. If one thread is running the "get" procedure, another could be running the "set" procedure at the same time.

If you want to use "get" and "set" procedures, you will need to add code to both procedures to manually synchronize access to the variable.

An alternative is to combine both "get" and "set" in one get-set procedure. It could have a separate parameter to indicate the required function, or it could have an optional parameter, which if passed, would provide the "set" function; the "get" function would always be provided since the procedure would always return a value.

However, even using a single "get-set" procedure may not provide adequate thread-safety for the variable. If you want to modify a variable using its previous value, such as adding one to the variable, you might think that getting the value of the variable, and then setting it to a new value in the same statement would work. However, another thread might call the procedure between your two calls to the procedure. Your second "set" call to the procedure would incorrectly overwrite the value that had been set by the other thread.

      // If myFld has the value 2 before this statement is run, the first call
      // would return 2.  The second call would set the value to 3.  If another
      // thread had set the value to 15 in between the calls, the second call 
      // should logically set it to 16, not to 3.
      getSetMyFld                    // second call to getSetMyFld, to set the value
             (getSetMyFld() + 1);    // first call to getSetMyFld, to get the value

If you need to perform more than one access to a variable without another thread being able to get or set the variable while you are performing the operation, you must use some manual synchronization to control all access to the variable. All users of that variable must use the same synchronization mechanism.



[ Top of Page | Previous Page | Next Page | Contents | Index ]