lava / linear_ringbuffer

A C++ ringbuffer that always looks like a flat array
GNU Affero General Public License v3.0
81 stars 13 forks source link

thread safe io_buffer #1

Open mipac opened 4 years ago

mipac commented 4 years ago

I'd like to use io_buffer from a reader thread and a writer thread How can I do it safely and efficiently?

lava commented 4 years ago

The only way I see is to mutex the whole buffer, i.e.

// Reader thread
{ std::lock_guard<std::mutex> lock(io_mutex);
  io_buffer.read(...);
}

// Writer thread
{ std::lock_guard<std::mutex> lock(io_mutex);
  io_buffer.write(...);
}

Even if you're willing to patch the io_buffer to allow finer-grained locking, I don't really see a good way to implement this. The problem is the resetting of the read/write position when the buffer is completely empty, so both threads really need to be able to change the write position.

Of course, an alternative would be to just use the linear_ringbuffer instead, which supports that use case natively.

mipac commented 4 years ago

ok thank you for reply

Le mer. 18 déc. 2019 à 17:47, Benno Evers notifications@github.com a écrit :

The only way I see is to mutex the whole buffer, i.e.

// Reader thread { std::lock_guard lock(io_mutex); io_buffer.read(...); }

// Writer thread { std::lock_guard lock(io_mutex); io_buffer.write(...); }

Even if you're willing to patch the io_buffer to allow finer-grained locking, I don't really see a good way to implement this. The problem is the resetting of the read/write position when the buffer is completely empty, so both threads really need to be able to change the write position.

Of course, an alternative would be to just use the linear_ringbuffer instead, which supports that use case natively.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/lava/linear_ringbuffer/issues/1?email_source=notifications&email_token=ABMPSA52YFLOVFICOECP3X3QZJHZZA5CNFSM4J4LVNIKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEHGX7LQ#issuecomment-567115694, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABMPSA5NBKLLMSN5FYFTQYTQZJHZZANCNFSM4J4LVNIA .