Is a memory barrier needed when using boost :: lockfree :: spsc_queue?

I am looking at Increase Skip Lockout .

When the producer thread pushes the data of the struct T into the buffer, it gets a copy (via the copy constructor) into the buffer.

When a consumer thread tries to call consume_one () to read an item in the buffer, does it seem like a memory barrier is needed? If not, how is it possible that the change made by the producer thread is visible to the consumer thread?

Thank!

+3


source to share


1 answer


No additional memory barrier is required.

The queue works correctly when indexes are read in memory memory order and written in memory free order: http://en.cppreference.com/w/cpp/atomic/memory_order

  • Acquisition: A load operation with this memory order performs a receive operation on the affected memory location: previous writes made to other memory locations by the thread that made the deallocation become visible in this thread.
  • Release: a save operation with this memory order performs a deallocation operation: previous writes to other memory locations become visible to threads that consume or acquire at the same location.

As you can see, there is no need to worry about writing to the actual item data, since the index update (which is done after copying) happens before the read.




Since the documented requirements for using SPSC queues clearly state that both the consumer and producer will always be the same, single, threads, all "local" index manipulations are performed with a "relaxed" memory order.

Note that the only operation that differs from it is reset()

that, while similar to construct / destruction, it is not thread safe.

For backups in memory order I recommend Anthony William's excellent book C ++ Concurrency In Action

+4


source







All Articles