golock

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2020 License: MIT Imports: 4 Imported by: 2

README

golock

travis go report card coverage godocs

Very simple (<100 LOC) file locking with optional timeouts.

Install

go get github.com/schollz/golock

Usage

Initialize the lock and then obtain it. If you specify the timeout and interval, it will poll at the given interval for the specified time until it successfully gets a lock, otherwise throw an error. If you don't specify the timeout, then it will throw an error immediately if it does not obtain the lock.

If you get no errors from locking, then you are good to go. Make sure to unlock it when you are done.

// first initiate lockfile
l := golock.New(
    golock.OptionSetName("mylockfile"), 
    golock.OptionSetInterval(1*time.Millisecond), 
    golock.OptionSetTimeout(60*time.Second),
)

// lock it
err := l.Lock()
if err != nil {
    // error means we didn't get the lock
    // handle it
}

// do stuff

// unlock it
err = l.Unlock()
if err != nil {
    panic(err)
}

Benchmarks

goos: linux
goarch: amd64
pkg: github.com/schollz/golock
BenchmarkLocking-4     200000     12224 ns/op    128 B/op    5 allocs/op

Contributing

Pull requests are welcome. Feel free to...

  • Revise documentation
  • Add new features
  • Fix bugs
  • Suggest improvements

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Lock

type Lock struct {
	// contains filtered or unexported fields
}

Lock is the structure for containing the lock attributes.

func New

func New(options ...Option) *Lock

New creates a new lock with the specified options. If no name is specified with the options, the default name is "golock.lock".

func (*Lock) Lock

func (l *Lock) Lock() (err error)

Lock will try to lock by creating a new file. If the file exists, it will throw an error, unless you are using timeouts in which case it will poll until it can create the file. If it is still unable to create the file it will throw an error.

func (*Lock) Unlock

func (l *Lock) Unlock() (err error)

Unlock will remove the file that it used for locking

type Option

type Option func(l *Lock)

Option is the type all options need to adhere to

func OptionSetInterval

func OptionSetInterval(interval time.Duration) Option

OptionSetInterval sets the interval to check (default: none)

func OptionSetName

func OptionSetName(name string) Option

OptionSetName sets the name

func OptionSetTimeout

func OptionSetTimeout(timeout time.Duration) Option

OptionSetTimeout sets the timeout (default: none)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL