Skip to content

Commit f6f14d8

Browse files
author
Mariano Gappa
authored
Merge pull request #10 from marianogappa/fix_print_race
Fixes print race using a mutex
2 parents 6b40372 + 37bc6ec commit f6f14d8

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

main.go

+8-10
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ type database struct {
2424
}
2525

2626
var help = flag.Bool("help", false, "shows usage")
27+
var printLock sync.Mutex
2728

2829
func init() {
2930
flag.BoolVar(help, "h", false, "shows usage")
@@ -61,9 +62,6 @@ func main() {
6162
targetDatabases = append(targetDatabases, k)
6263
}
6364

64-
out := make(chan string)
65-
go println(out)
66-
6765
quitContext, cancel := context.WithCancel(context.Background())
6866
go awaitSignal(cancel)
6967

@@ -74,7 +72,7 @@ func main() {
7472
for _, k := range targetDatabases {
7573
go func(db database, k string) {
7674
defer wg.Done()
77-
if r := runSQL(quitContext, db, sql, k, len(targetDatabases) > 1, out); !r {
75+
if r := runSQL(quitContext, db, sql, k, len(targetDatabases) > 1); !r {
7876
returnCode = 1
7977
}
8078
}(databases[k], k)
@@ -84,7 +82,7 @@ func main() {
8482
os.Exit(returnCode)
8583
}
8684

87-
func runSQL(quitContext context.Context, db database, sql string, key string, prependKey bool, out chan string) bool {
85+
func runSQL(quitContext context.Context, db database, sql string, key string, prependKey bool) bool {
8886
userOption := ""
8987
if db.User != "" {
9088
userOption = fmt.Sprintf("-u %v ", db.User)
@@ -136,7 +134,7 @@ func runSQL(quitContext context.Context, db database, sql string, key string, pr
136134

137135
scanner := bufio.NewScanner(stdout)
138136
for scanner.Scan() {
139-
out <- prepend + scanner.Text()
137+
println(prepend + scanner.Text())
140138
}
141139

142140
stderrLines := []string{}
@@ -159,10 +157,10 @@ func runSQL(quitContext context.Context, db database, sql string, key string, pr
159157
return result
160158
}
161159

162-
func println(ss chan string) {
163-
for s := range ss {
164-
fmt.Println(s)
165-
}
160+
func println(s string) {
161+
printLock.Lock()
162+
defer printLock.Unlock()
163+
fmt.Println(s)
166164
}
167165

168166
func readInput(r io.Reader) string {

0 commit comments

Comments
 (0)