Is this use of volatile in TBB bug?

  c++, multithreading, race-condition, volatile

Recently Eric Niebler had a tweet about volatile and thread safety and somebody replied with the link to following code from Intel TBB.

void Block::shareOrphaned(intptr_t binTag, unsigned index)
{
    MALLOC_ASSERT( binTag, ASSERT_TEXT );
    // unreferenced formal parameter warning
    tbb::detail::suppress_unused_warning(index);
    STAT_increment(getThreadId(), index, freeBlockPublic);
    markOrphaned();
    if ((intptr_t)nextPrivatizable==binTag) {
        // First check passed: the block is not in mailbox yet.
        // Need to set publicFreeList to non-zero, so other threads
        // will not change nextPrivatizable and it can be zeroed.
        if ( !readyToShare() ) {
            // another thread freed an object; we need to wait until it finishes.
            // There is no need for exponential backoff, as the wait here is not for a lock;
            // but need to yield, so the thread we wait has a chance to run.
            // TODO: add a pause to also be friendly to hyperthreads
            int count = 256;
            while( (intptr_t)const_cast<Block* volatile &>(nextPrivatizable)==binTag ) {
                if (--count==0) {
                    do_yield();
                    count = 256;
                }
            }
        }
    }
    MALLOC_ASSERT( publicFreeList.load(std::memory_order_relaxed) !=NULL, ASSERT_TEXT );
    // now it is safe to change our data
    previous = NULL;
    // it is caller responsibility to ensure that the list of blocks
    // formed by nextPrivatizable pointers is kept consistent if required.
    // if only called from thread shutdown code, it does not matter.
    (intptr_t&)(nextPrivatizable) = UNUSABLE;
}

as an example of wrong use of volatile (since it guarantees nothing wrt threading).

Is this really a bug?

My first intuition is yes, but then again TBB is not some anon person github project, so I am curious if I am missing something.

github link

Source: Windows Questions C++

LEAVE A COMMENT