Files
ai_academy/internal/localsandbox/rootlock.go
T
runny 7ec21f35b0 chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
2026-11-16 18:12:23 +08:00

63 lines
1.2 KiB
Go

package localsandbox
import (
"path/filepath"
"runtime"
"strings"
"sync"
)
type rootLocks struct {
mu sync.Mutex
locks map[string]*rootLease
}
type rootLease struct {
mu sync.Mutex
refs int
}
func newRootLocks() *rootLocks {
return &rootLocks{locks: make(map[string]*rootLease)}
}
func rootLockKey(root string) string {
key := filepath.Clean(root)
if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
key = strings.ToLower(key)
}
return key
}
// LockRoot serializes mutating work against one workspace directory.
// Sessions that share a project share the lock; different directories do not
// block each other. The returned function always unlocks; call it with defer.
func (s *Service) LockRoot(root string) func() {
if s == nil || s.roots == nil || strings.TrimSpace(root) == "" {
return func() {}
}
return s.roots.lock(root)
}
func (r *rootLocks) lock(root string) func() {
key := rootLockKey(root)
r.mu.Lock()
lease := r.locks[key]
if lease == nil {
lease = &rootLease{}
r.locks[key] = lease
}
lease.refs++
r.mu.Unlock()
lease.mu.Lock()
return func() {
lease.mu.Unlock()
r.mu.Lock()
lease.refs--
if lease.refs == 0 {
delete(r.locks, key)
}
r.mu.Unlock()
}
}