martin s
martin s

Reputation: 1131

Atomic function without locks to change two independent memory locations

I have the following function called updateEntry which writes a value into a lookup table. I would like to create a multi-threaded version of this function. I was looking into the atomic operation __sync_bool_compare_and_swap but I am not sure how to apply it here properly.

Is it theoretical possible to implement this function atomically without locking, since it change two independent memory locations entryLookup[id] and entry?

   void updateEntry(Entry ** entryLookup, unsigned int id, int val1, short val2){
            Entry * entry     = entryLookup[id];
            entry->val1       = val1;
            entry->val2       = val2;
            entryLookup[id]  += sizeof(Entry);
   }

Upvotes: 0

Views: 123

Answers (1)

peppincsoda
peppincsoda

Reputation: 36

To make this thread-safe, you could increment entryLookup[id] first to make sure any other thread that comes later cannot change the same entry, and then fill in the values. An atomic addition is needed where the old value is returned:

void updateEntry(Entry ** entryLookup, unsigned int id, int val1, short val2)
{
    Entry * entry = __sync_fetch_and_add(&entryLookup[id], sizeof(Entry));
    entry->val1   = val1;
    entry->val2   = val2;
}

Upvotes: 1

Related Questions