github.com/searKing/golang/go@v1.2.74/sync/atomic/file.go (about)

     1  // Copyright 2021 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package atomic
     6  
     7  import (
     8  	"fmt"
     9  	"io/ioutil"
    10  	"os"
    11  )
    12  
    13  // File is an atomic wrapper around a file.
    14  type File string
    15  
    16  func (m *File) TryLock() error {
    17  	if m == nil {
    18  		return fmt.Errorf("nil pointer")
    19  	}
    20  	if *m == "" {
    21  		temp, err := ioutil.TempFile("", "file_lock_")
    22  		if err != nil {
    23  			return err
    24  		}
    25  		*m = File(temp.Name())
    26  		_ = temp.Close()
    27  		return nil
    28  	}
    29  
    30  	f, err := os.OpenFile(string(*m), os.O_CREATE|os.O_EXCL, 0600)
    31  	if err != nil {
    32  		// Can't lock, just return
    33  		return err
    34  	}
    35  	_ = f.Close()
    36  	return nil
    37  }
    38  
    39  func (m *File) TryUnlock() error {
    40  	if m == nil || *m == "" {
    41  		return nil
    42  	}
    43  	return os.Remove(string(*m))
    44  }