github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/runner.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors All rights reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"sync"
    21  )
    22  
    23  // Runner is an abstraction to make it easy to start and stop groups of things that can be
    24  // described by a single function which waits on a channel close to exit.
    25  type Runner struct {
    26  	lock      sync.Mutex
    27  	loopFuncs []func(stop chan struct{})
    28  	stop      *chan struct{}
    29  }
    30  
    31  // NewRunner makes a runner for the given function(s). The function(s) should loop until
    32  // the channel is closed.
    33  func NewRunner(f ...func(stop chan struct{})) *Runner {
    34  	return &Runner{loopFuncs: f}
    35  }
    36  
    37  // Start begins running.
    38  func (r *Runner) Start() {
    39  	r.lock.Lock()
    40  	defer r.lock.Unlock()
    41  	if r.stop == nil {
    42  		c := make(chan struct{})
    43  		r.stop = &c
    44  		for i := range r.loopFuncs {
    45  			go r.loopFuncs[i](*r.stop)
    46  		}
    47  	}
    48  }
    49  
    50  // Stop stops running.
    51  func (r *Runner) Stop() {
    52  	r.lock.Lock()
    53  	defer r.lock.Unlock()
    54  	if r.stop != nil {
    55  		close(*r.stop)
    56  		r.stop = nil
    57  	}
    58  }