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

Issue with chapter09/concurrency/once/main.go #3

Open
rhysmeister opened this issue Dec 14, 2023 · 1 comment
Open

Issue with chapter09/concurrency/once/main.go #3

rhysmeister opened this issue Dec 14, 2023 · 1 comment

Comments

@rhysmeister
Copy link

Hello,

I had an issue with the execution of this example. With the default code I got the following output (nearly always, once or two I got two "Hello, friend!" messages...

https://github.com/PacktPublishing/Test-Driven-Development-in-Go/blob/main/chapter09/concurrency/once/main.go

~/git/Test-Driven-Development-in-Go/chapter09/concurrency/once$ go run main.go
Hello, friend!
Channel closed.
Goodbye, friend!

Fixed it with wait groups but perhaps there's a simpler way...

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

func safelyClose(once *sync.Once, ch chan struct{}) {
	defer wg.Done()
	fmt.Println("Hello, friend!")
	once.Do(func() {
		fmt.Println("Channel closed.")
		close(ch)
	})
}

func main() {
	var once sync.Once

	ch := make(chan struct{})
	for i := 0; i < 3; i++ {
		wg.Add(1)
		go safelyClose(&once, ch)
	}
	<-ch
	wg.Wait()
	fmt.Println("Goodbye, friend!")
}

~/git/Test-Driven-Development-in-Go/chapter09/concurrency/once$ go run main.go
Hello, friend!
Channel closed.
Hello, friend!
Hello, friend!
Goodbye, friend!

@rhysmeister
Copy link
Author

rhysmeister commented Dec 14, 2023

Hello,

Also had similar issues with other bit of this chapter, for example concurrency/data-races and concurrency/buffered-channels. I'm using go version 1.21.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant