github.com/hartzell/terraform@v0.8.6-0.20180503104400-0cc9e050ecd4/synchronized_writers.go (about)

     1  package main
     2  
     3  import (
     4  	"io"
     5  	"sync"
     6  )
     7  
     8  type synchronizedWriter struct {
     9  	io.Writer
    10  	mutex *sync.Mutex
    11  }
    12  
    13  // synchronizedWriters takes a set of writers and returns wrappers that ensure
    14  // that only one write can be outstanding at a time across the whole set.
    15  func synchronizedWriters(targets ...io.Writer) []io.Writer {
    16  	mutex := &sync.Mutex{}
    17  	ret := make([]io.Writer, len(targets))
    18  	for i, target := range targets {
    19  		ret[i] = &synchronizedWriter{
    20  			Writer: target,
    21  			mutex:  mutex,
    22  		}
    23  	}
    24  	return ret
    25  }
    26  
    27  func (w *synchronizedWriter) Write(p []byte) (int, error) {
    28  	w.mutex.Lock()
    29  	defer w.mutex.Unlock()
    30  	return w.Writer.Write(p)
    31  }