Exemple #1
0
func (c *Container) acquireLock(name string) (*lockfile.Lockfile, error) {
	lock, err := lockfile.New(fmt.Sprintf("/tmp/lxc-%s.lock", name))
	if err != nil {
		log.Printf("Cannot initialize lock: %s", err)
		return nil, err
	}

	startTime := time.Now()
	for {
		err = lock.TryLock()
		if err != nil {
			if time.Since(startTime) > lockTimeout {
				return nil, err
			}

			if err == lockfile.ErrBusy {
				log.Printf(`Lock "%v" is busy - retrying in 3 seconds`, lock)
				time.Sleep(3 * time.Second)
				continue
			}
		} else {
			return lock, nil
		}
	}
}
func ExampleLockfile() {
	lock, err := lockfile.New("/tmp/lock.me.now.lck")
	if err != nil {
		fmt.Printf("Cannot init lock. reason: %s\n", err)
		panic(err)
	}
	err = lock.TryLock()

	// Error handling is essential, as we only try to get the lock.
	if err != nil {
		fmt.Printf("Cannot lock \"%v\", reason: %s\n", lock, err)
		panic(err)
	}

	defer lock.Unlock()

	fmt.Println("Do stuff under lock")
	// Output: Do stuff under lock
}