Created
September 15, 2012 20:06
-
-
Save ridiculousfish/3729531 to your computer and use it in GitHub Desktop.
A (buggy) thread safe set written in Go
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
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