]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Delete only expired entries from fdCache
authorSergey Matveev <stargrave@stargrave.org>
Mon, 28 Nov 2022 14:42:49 +0000 (17:42 +0300)
committerSergey Matveev <stargrave@stargrave.org>
Fri, 13 Jan 2023 08:32:42 +0000 (11:32 +0300)
storage/file.go

index 7a5bc33dc7820493c9a4abe98d00b75ff0f869f6..aa67df15f486f463fd3a47554ecc83d0691009dc 100644 (file)
@@ -15,8 +15,11 @@ import (
        "github.com/anacrolix/torrent/segments"
 )
 
+const fdCacheAliveTime = 10
+
 type fdCacheEntry struct {
-       fd *os.File
+       last int64
+       fd   *os.File
        sync.Mutex
 }
 
@@ -30,20 +33,24 @@ var (
 )
 
 func fdCacheCleaner() {
-       cleaner := func(c *map[string]*fdCacheEntry, m *sync.Mutex) {
+       cleaner := func(c map[string]*fdCacheEntry, m *sync.Mutex) {
+               now := time.Now().Unix()
                m.Lock()
-               prev := fdRCache
-               *c = make(map[string]*fdCacheEntry)
-               m.Unlock()
-               for _, v := range prev {
-                       v.Lock()
-                       v.fd.Close()
-                       v.Unlock()
+               for k, v := range c {
+                       if now-v.last > fdCacheAliveTime {
+                               go func() {
+                                       v.Lock()
+                                       v.fd.Close()
+                                       v.Unlock()
+                               }()
+                       }
+                       delete(c, k)
                }
+               m.Unlock()
        }
-       for range time.Tick(10 * time.Second) {
-               cleaner(&fdRCache, &fdRCacheM)
-               cleaner(&fdWCache, &fdWCacheM)
+       for range time.Tick(fdCacheAliveTime * time.Second) {
+               cleaner(fdRCache, &fdRCacheM)
+               cleaner(fdWCache, &fdWCacheM)
        }
 }
 
@@ -199,6 +206,7 @@ func (fst *fileTorrentImplIO) readFileAt(file file, b []byte, off int64) (n int,
                b = b[:file.length-off]
        }
        centry.Lock()
+       centry.last = time.Now().Unix()
        n, err = centry.fd.ReadAt(b, off)
        centry.Unlock()
        return
@@ -242,6 +250,7 @@ func (fst fileTorrentImplIO) WriteAt(p []byte, off int64) (n int, err error) {
                fdWCacheM.Unlock()
                var n1 int
                centry.Lock()
+               centry.last = time.Now().Unix()
                n1, err = centry.fd.WriteAt(p[:e.Length], e.Start)
                centry.Unlock()
                n += n1