Create a gist now

Instantly share code, notes, and snippets.

A (buggy) thread safe set written in Go
package main
import (
"fmt"
)
type SetTest struct {
val string
result chan bool
}
type SafeSet struct {
set map[string] bool
adder chan string
tester chan SetTest
remover chan string
}
func (set *SafeSet) add(s string) {
set.adder <- s
}
func (set *SafeSet) remove(s string) {
set.remover <- s
}
func (set *SafeSet) get(s string) bool {
request := SetTest{s, make(chan bool)}
set.tester <- request
return <- request.result
}
func (set *SafeSet) run() {
for {
select {
case toadd := <- set.adder:
set.set[toadd] = true
case toremove := <- set.remover:
delete(set.set, toremove)
case testreq := <- set.tester:
testreq.result <- set.set[testreq.val]
}
}
}
func newSet() (result SafeSet) {
result.set = make(map[string] bool)
result.adder = make(chan string, 16)
result.tester = make(chan SetTest, 16)
result.remover = make(chan string)
go result.run()
return
}
func main() {
set := newSet()
set.add("First")
set.add("Second")
set.add("Third")
present := set.get("Third")
fmt.Println(present)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment