From: qydysky Date: Sat, 1 Aug 2020 00:16:50 +0000 (+0800) Subject: 19 X-Git-Tag: v0.0.2~69 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=e1e95b3fc6006290e44a097c122e6a26713856a7;p=part%2F.git 19 --- diff --git a/Lock.go b/Lock.go index 007df31..eaf8a2f 100644 --- a/Lock.go +++ b/Lock.go @@ -1,52 +1,58 @@ package part -// import ( -// "os" -// "sync" -// ) - -// type lock struct { -// sync.Mutex -// } - -// var ( -// lock_file *os.File -// lock_md5Key string -// ) - -// func Lock() *lock { -// return &lock{} -// } - -// func (l *lock) Start(filePath string) int { -// l.Lock() -// defer l.Unlock() - -// if l.State() {return 1} -// if !Checkfile().IsExist(filePath) {return 3} - -// fi, err := os.Stat(filePath) -// if err != nil {return 4} -// if Sys().Check(fi.Name())[0] != 0 {return 2} - -// // lock_md5Key = ".lock." + fi.Name() -// // lock_file, _ = os.Create(lock_md5Key) -// return 0 -// } - -// func (l *lock) Stop() int { -// l.Lock() -// defer l.Unlock() - -// if !l.State() {return 1} -// if !Checkfile().IsExist(lock_md5Key) {return 2} - -// lock_file.Close() -// os.Remove(lock_md5Key) -// lock_md5Key = "" -// return 0 -// } - -// func (*lock) State() bool { -// return lock_md5Key != "" -// } \ No newline at end of file +import ( + "os" + "sync" + "time" + "errors" +) + +type lock struct { + sync.Mutex +} + +var ( + lock_file string + lock_timeout int64 = 10 +) + +func Lock() *lock { + return &lock{} +} + +func (l *lock) Start(filePath string,timeout int64) error { + l.Lock() + defer l.Unlock() + + if e,t := Checkfile().GetFileModTime(filePath); e != nil || time.Now().Unix() - t <= lock_timeout { + Logf().E(e.Error(),"or still alive") + return errors.New("still alive") + } + + lock_file = filePath + lock_timeout = timeout + + go func(){ + for lock_file != "" { + File().FileWR(Filel{ + File:filePath, + Write:true, + Loc:0, + Context:"still alive", + }) + Sys().Timeoutf(int(lock_timeout)) + } + }() + + return nil +} + +func (l *lock) Stop() { + l.Lock() + defer l.Unlock() + + lock_file = "" + + os.RemoveAll(lock_file) + +} \ No newline at end of file