Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

main: synchronize writes to VT100-faker on Windows #14194

Merged
merged 1 commit into from
May 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,15 @@ func copyOutput(r io.Reader, doneCh chan<- struct{}) {
if runtime.GOOS == "windows" {
stdout = colorable.NewColorableStdout()
stderr = colorable.NewColorableStderr()

// colorable is not concurrency-safe when stdout and stderr are the
// same console, so we need to add some synchronization to ensure that
// we can't be concurrently writing to both stderr and stdout at
// once, or else we get intermingled writes that create gibberish
// in the console.
wrapped := synchronizedWriters(stdout, stderr)
stdout = wrapped[0]
stderr = wrapped[1]
}

var wg sync.WaitGroup
Expand Down
31 changes: 31 additions & 0 deletions synchronized_writers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"io"
"sync"
)

type synchronizedWriter struct {
io.Writer
mutex *sync.Mutex
}

// synchronizedWriters takes a set of writers and returns wrappers that ensure
// that only one write can be outstanding at a time across the whole set.
func synchronizedWriters(targets ...io.Writer) []io.Writer {
mutex := &sync.Mutex{}
ret := make([]io.Writer, len(targets))
for i, target := range targets {
ret[i] = &synchronizedWriter{
Writer: target,
mutex: mutex,
}
}
return ret
}

func (w *synchronizedWriter) Write(p []byte) (int, error) {
w.mutex.Lock()
defer w.mutex.Unlock()
return w.Writer.Write(p)
}