Is this thread safe?

dsimcha dsimcha at yahoo.com
Fri Jul 11 14:53:48 PDT 2008


I'm very new to concurrent programming and am trying to implement some high
performance math stuff in D.  Could someone please tell me whether the
following simple function would be considered thread safe?

real logFactorial(uint n) {
    static real* factorial_table = ([0.0L]).ptr;
    static size_t length = 1;
    //Length is guaranteed to never decrease.
    //At least at an abstract level, the synchronized part is guaranteed to
    //only write to elements >= length.
    if(length > n) return factorial_table[n];
    synchronized {
        if(capacity(factorial_table) < (n + 1) * real.sizeof) {
            //Is it safe to update the factorial_table pointer like this?
            factorial_table = cast(real*) realloc(factorial_table, (n + 1) *
real.sizeof);
        }
        for(uint i = length; i<=n; i++) {
            factorial_table[i] = factorial_table[i-1] + log2(i);
        }
        //Set new length after all numbers are calculated.
        length = n;
        return factorial_table[n];
    }
}

This function computes the log of the factorial of n, and caches the results.
 If it's possible without resorting to any low-level tricks that would make
this function horribly unreadable, I'd like to avoid having the reads of
factorial_table synchronized for performance reasons.  I would guess that
updating pointers and size_t variables (which are of the same representation
as pointers, at least on the architectures I'm aware of) should be atomic,
since otherwise the GC would not be able to properly scan pointers that were
in the middle of being updated.



More information about the Digitalmars-d mailing list