In the below C99 example, is the buffer_full
flag guaranteed to be set (even with -O2 optimizations enabled) after the buffer is read or written to? Or, do I need a memory barrier to ensure correct ordering?
I expect this to be run on a system where aligned 32-bit reads and writes are atomic.
Assume only one instance of each thread is being run and no other threads are accessing buffer
or buffer_full
.
char buffer[100];
int buffer_full;
// write interesting data to the buffer. does not read.
void fill_buffer(char* buffer, size_t buffsz);
// read the interesting data in the buffer. does not write.
void use_buffer(const char* buffer, size_t buffsz);
void writer_thread()
{
if (!buffer_full) {
fill_buffer(buffer, sizeof(buffer));
// is a memory barrier needed here?
buffer_full = 1;
}
}
void reader_thread()
{
if (buffer_full) {
use_buffer(buffer, sizeof(buffer));
// is a memory barrier needed here?
buffer_full = 0;
}
}