Created
March 24, 2021 16:47
-
-
Save uloureiro/8a41708920fc5fc0cfc30b718ae7a913 to your computer and use it in GitHub Desktop.
Data Set and Concurrency in Go with Channels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://play.golang.org/p/b7lYcShM2kC | |
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
type Set struct { | |
values map[int]interface{} | |
mu sync.Mutex | |
} | |
func (s *Set) List() []int { | |
s.mu.Lock() | |
defer s.mu.Unlock() | |
var result []int | |
for k := range s.values { | |
result = append(result, k) | |
} | |
return result | |
} | |
func (s *Set) Add(item int) { | |
s.mu.Lock() | |
defer s.mu.Unlock() | |
s.values[item] = nil | |
} | |
func NewSet() *Set { | |
return &Set{ | |
values: make(map[int]interface{}), | |
} | |
} | |
func main() { | |
s := NewSet() | |
foo := func(s *Set, c chan int, values ...int) { | |
defer close(c) | |
for i, v := range values { | |
s.Add(v) | |
c <- i | |
} | |
} | |
values := []int{1, 2, 3, 5, 1} | |
c := make(chan(int), len(values)) | |
go foo(s, c, values...) | |
select { | |
case <- c: | |
} | |
fmt.Println(s.List()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment