diff options
author | Martin Czygan <martin.czygan@gmail.com> | 2021-07-05 23:24:47 +0200 |
---|---|---|
committer | Martin Czygan <martin.czygan@gmail.com> | 2021-07-05 23:24:47 +0200 |
commit | 3a8af268f74a3abc2389306be030ee42c0fc7120 (patch) | |
tree | 87f8e4a5f8400cb0fefbbc5ddb33721dc515f84d /skate | |
parent | f33ef23e0889430016cf8363e914b73313758714 (diff) | |
download | refcat-3a8af268f74a3abc2389306be030ee42c0fc7120.tar.gz refcat-3a8af268f74a3abc2389306be030ee42c0fc7120.zip |
add thread safe writer
Diffstat (limited to 'skate')
-rw-r--r-- | skate/xio/util.go | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/skate/xio/util.go b/skate/xio/util.go index 4fc8905..49f38a3 100644 --- a/skate/xio/util.go +++ b/skate/xio/util.go @@ -6,8 +6,28 @@ import ( "io" "os" "strings" + "sync" ) +// SingleWriter makes any writer thread safe. +type SingleWriter struct { + sync.Mutex + w io.Writer +} + +// NewSingleWriter returns an io.Writer that can be safely accessed by multiple +// goroutines. +func NewSingleWriter(w io.Writer) *SingleWriter { + return &SingleWriter{w: w} +} + +// Write wraps the underlying writer and gives exclusive access. +func (w *SingleWriter) Write(p []byte) (n int, err error) { + w.Lock() + defer w.Unlock() + return w.w.Write(p) +} + // OpenTwo opens two files. The caller needs to check for a single error only. func OpenTwo(f0, f1 string) (g0, g1 *os.File, err error) { if g0, err = os.Open(f0); err != nil { |