This question evaluates a candidate's ability to implement buffered I/O and design concurrency-safe APIs, exercising skills in data buffering, performance optimization, and thread-safety.
You are given a simple file writer class that writes data directly to disk:
class FileWriter {
public:
// Append `data` to the file on disk immediately (no buffering).
// May be relatively slow because it calls the OS for each write.
void write(const std::string& data);
// Flush any OS-level buffers to disk.
void flush();
};
This class is already implemented for you.
Implement a BufferedFileWriter class that uses an internal memory buffer to reduce the number of calls to the underlying FileWriter:
Requirements:
BufferedFileWriter
should have the following public interface (you may use composition or inheritance, but composition is preferred):
class BufferedFileWriter {
public:
BufferedFileWriter(FileWriter& underlying, size_t buffer_capacity);
// Append `data` to an in-memory buffer.
// Only when certain conditions are met (e.g., the buffer is full),
// data should be flushed to the underlying FileWriter.
void write(const std::string& data);
// Force all currently buffered data to be written to the
// underlying FileWriter and then flush it to disk.
void flush();
};
FileWriter
instance and a
buffer_capacity
in bytes.
write
should:
data
to an internal memory buffer.
buffer_capacity
, it should write the buffered data to the underlying
FileWriter
and clear the internal buffer.
flush
should:
FileWriter
(if the buffer is not empty).
flush()
on the underlying
FileWriter
.
buffer_capacity
.
buffer_capacity
and then calling
flush()
.
buffer_capacity
and ensuring data is flushed at the right times.
flush()
calls with an empty buffer are safe.
You do not need to implement the real file I/O of FileWriter; only show the code for BufferedFileWriter using the given interface.
BufferedFileWriter thread-safeNow assume that BufferedFileWriter may be used from multiple threads concurrently. Different threads may call write() and flush() at the same time.
BufferedFileWriter
is
thread-safe
.
write()
and
flush()
from all threads are executed in some serial order, and data is not corrupted or lost.
write()
and
flush()
coordinate with each other.
Assume you may use standard synchronization primitives such as mutexes/locks and condition variables if needed.