From d3bce4731b6ead21c75f2fe7608f3aa8d5dced39 Mon Sep 17 00:00:00 2001 From: Jian Han Date: Wed, 22 Nov 2017 16:42:17 +1000 Subject: [PATCH] added init and sem --- init/main.go | 13 ++++++++++++ semaphore/main.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 init/main.go create mode 100644 semaphore/main.go diff --git a/init/main.go b/init/main.go new file mode 100644 index 0000000..c846a55 --- /dev/null +++ b/init/main.go @@ -0,0 +1,13 @@ +package main + +import ( + "github.com/davecgh/go-spew/spew" +) + +func init() { + spew.Dump("inited") +} + +func main() { + spew.Dump("Test") +} diff --git a/semaphore/main.go b/semaphore/main.go new file mode 100644 index 0000000..a2ac61a --- /dev/null +++ b/semaphore/main.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "sync" + "time" +) + +func main() { + + // a blocking channel to keep concurrency under control + semaphoreChan := make(chan struct{}, 10) + defer close(semaphoreChan) + + // a wait group enables the main process a wait for goroutines to finish + wg := sync.WaitGroup{} + + // a simple loop from 1 to 10 + for i := 1; i <= 100; i++ { + + // increment the wait group internal counter + wg.Add(1) + + // print what we're about to be doing (will keep the order) + fmt.Printf("About to run #%d in a goroutine\n", i) + + // fire off a goroutine with the index in a closure since it will be modified + go func(i int) { + + // block until the semaphore channel has room + // this could also be moved out of the goroutine + // which would make sense if the list is huge + semaphoreChan <- struct{}{} + + // pretend to do some synchronous work + time.Sleep(time.Second) + + // tell the wait group that we be done + wg.Done() + + // print an message containing the index (won't keep order) + fmt.Printf("About to exit #%d from a goroutine\n", i) + + // clear a spot in the semaphore channel + <-semaphoreChan + + }(i) + } + + // wait for all the goroutines to be done + wg.Wait() +}