Skip to content

Instantly share code, notes, and snippets.

@dimawebmaker
Last active January 5, 2018 09:47
Show Gist options
  • Save dimawebmaker/c6041390410fd82895d976c50af2a45b to your computer and use it in GitHub Desktop.
Save dimawebmaker/c6041390410fd82895d976c50af2a45b to your computer and use it in GitHub Desktop.
[Golang channels] Golang channels example #go #golang
package tasks
type Task struct {
Name string
}
func (t *Task) Finish() {
// what actually can finish the task
}
func AssignTasks(ch chan *Task) {
// we have 100 tasks to assigned.
// all we need to do is throw them all to the channel.
// when we finish, close the channel, the read end of channel will stop reading.
for i := 0; i < 100; i++ {
task := new(Task)
ch <- task
}
close(ch)
}
func WorkerFinishTasks(ch chan *Task, done chan struct{}) {
// Worker doesn't care what and how many tasks he do.
// He just finish all the tasks as possible as he can.
// when the channel closed, he will know all the task done.
for task := range ch {
task.Finish()
}
// send a signal the indicate that his work is done.
done <- struct{}{}
}
func main() {
workerNum := 4
ch := make(chan *Task, workerNum)
// use channel as an signal here, the struct{} type take zero byte in memory.
done := make(chan struct{}, workerNum)
go AssignTasks(ch)
for i:=0; i<workerNum; i++ {
go WorkerFinishTasks(ch, done)
}
// we hire 4 worker to work, so we need to receive 4 signal when they all done.
for i:=0; i<workerNum; i++ {
<-done
}
fmt.Println("all task done!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment