Thursday, 16 July 2009

Mutual Exclusion



Had a few thoughts about making the program thread-safe, and this involves ensuring mutual exclusion on a couple of functions.

First is the pop function for the stack containing all of the fid's of the topographic areas to be loaded. The function works like this:

string s = stack.top
stack.pop

Now, if two threads call it simultaneously, they could end up with the same reference, but pop two items off the stack. The following trace shows how:


Not only does this mean that one item gets loaded twice (waste of resources) but it means that one gets missed (b is not in the stack, nor in s1 or s2).

The other problem is adding these new items to the list to render. The process goes like this:

last.next = item
last = item

where last is a pointer to the last item in the list. This is a problem if last.next gets set by a different process before last, for instance:


item1 mysteriously disappears. This causes a memory leak, and incorrect rendering.

Using the built in Mutex structure in windows, these routines run in whole before another process is allowed to run them by being forced to wait until the mutex is available, for instance:

WaitForSingleObject(mutex)
critical section
ReleaseMutex(mutex)

At the moment, these are the only functions the extra threads are calling, so this makes the program safe.

No comments:

Post a Comment