Search code examples
c++memory-alignmentlock-free

Atomicity of writing a word (32/64bit) to a char array


I am currently building a new data structure that I will use as a circular array/hashmap with a single producer and single consumer.

The structure is a char array separated in "buckets" (say an array of 1024 bytes split in 4 256 bytes buckets), where I want to store binary data never larger than bucket size.

I want writers to basically never block on writing (and overwrite last entry when buffer full), and readers to be able to jump to a specific bucket number and read a "consistent" (doesnt need to be the latest) entry.

My idea for concurrency control is to use a kind of seqlock . While I could have one global seqlock for the structure, I wish to avoid cacheline contention by having one per "bucket". Therefore what I would like to do for writing to the array is this (seqlock idea):

  1. Write first 4/8 bytes of bucket with an ever increasing sequence number
  2. Acquire barrier
  3. Write rest of bucket data
  4. Release barrier
  5. Write first 4/8 bytes of bucket with an ever increasing sequence number

Basically the beginning of the bucket is used as a seqlock sequence number.

Now what I am concerned about is the atomicity of steps 1 and 4. What happens if I memcpy (char*)&sequence into the buffer? Is it atomic(i am guessing not)? Is there a way to make it atomic (by having properly aligned "buckets" for example)?


Solution

  • Well, I am interested in the general case of writing into a char array, but I guess the simplest way to circumvent the question is to have a bucket struct encompassing the sequence and a char[maxSize].