page_writer_pattern.go 971 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package mount
  2. import "sync/atomic"
  3. type WriterPattern struct {
  4. isSequentialCounter int64
  5. lastWriteStopOffset int64
  6. chunkSize int64
  7. }
  8. const ModeChangeLimit = 3
  9. // For streaming write: only cache the first chunk
  10. // For random write: fall back to temp file approach
  11. func NewWriterPattern(chunkSize int64) *WriterPattern {
  12. return &WriterPattern{
  13. isSequentialCounter: 0,
  14. lastWriteStopOffset: 0,
  15. chunkSize: chunkSize,
  16. }
  17. }
  18. func (rp *WriterPattern) MonitorWriteAt(offset int64, size int) {
  19. lastOffset := atomic.SwapInt64(&rp.lastWriteStopOffset, offset+int64(size))
  20. counter := atomic.LoadInt64(&rp.isSequentialCounter)
  21. if lastOffset == offset {
  22. if counter < ModeChangeLimit {
  23. atomic.AddInt64(&rp.isSequentialCounter, 1)
  24. }
  25. } else {
  26. if counter > -ModeChangeLimit {
  27. atomic.AddInt64(&rp.isSequentialCounter, -1)
  28. }
  29. }
  30. }
  31. func (rp *WriterPattern) IsSequentialMode() bool {
  32. return atomic.LoadInt64(&rp.isSequentialCounter) >= 0
  33. }