Go is very suitable for concurrent programming: add go in front of your function call, and you function will run on a separate goroutine (like a light thread)
And Channel is a very powerful feature in Go for communicating between goroutines
Unbuffered channel block on send and receive, meaning that a send will block until the other side: the receiver is ready to receive. It can be used for synchronising goroutines, and is a very simple way of communicating and you know exactly when the communication happens.
Where as buffered channel won't block even when no receiver is ready, but will block when the buffer is full. This fits quite well in a queue idea: when the queue is full, no new process can come in; when a process is done, another one can come in.
In this post, I'll build up a simple queue using the unbuffered channel feature in Go
Firstly let's mock out our process function:
func proc(p string) {
log.Println(p, "is processing")
time.Sleep(3 * time.Second)
log.Println("leaving", p)
}
And my main initially looks like this:
func main() {
jobs := []string{"p1", "p2", "p3", "p4", "p5"}
for _, p := range jobs {
proc(p)
}
log.Println("All done!")
}
So we mock out our jobs: a string slice consists of 5 elements. And we simply loop through the jobs and process each one.
Then we need to put them in a queue and run them in parallel. Whenever one finishes, another one starts:
func main() {
const n = 2
jobs := []string{"p1", "p2", "p3", "p4", "p5"}
queue := make(chan string, n)
for _, p := range jobs {
queue <- p
go func(p string) {
proc(p)
<-queue
}(p)
}
log.Println("All done!")
}
Here, we've defined a unbuffered channel with capacity of n, and put proc into a anonymouse function and put it onto a goroutine. We send p to the queue and take out one from the queue after proc finishes. Deadly easy.
But the program will not do anything and directly exit, because main won't wait for all the goroutines to finish.
We need to add a wait group to wait for all goroutines to finish. Foutunately Go's got a rich standard library, and we can use sync.WaitGroup to do this.
Here is the full program:
package main
import (
"log"
"os"
"sync"
"time"
)
func main() {
log.SetOutput(os.Stdout)
const n = 2
jobs := []string{"p1", "p2", "p3", "p4", "p5"}
var wg sync.WaitGroup
queue := make(chan string, n)
for _, p := range jobs {
queue <- p
wg.Add(1)
go func(p string) {
proc(p)
<-queue
wg.Done()
}(p)
}
wg.Wait()
log.Println("All done!")
}
func proc(p string) {
log.Println(p, "is processing")
time.Sleep(3 * time.Second)
log.Println("leaving", p)
}
You can run the code HERE in the browser
2 comments:
Thanks for the post ;)
borse firmateborsa e finanza ma vai gli davanti fuori
Furse was richly rewarded on her behalf performance by the LSE compensation committee having a bonus exceeding guidelines, making the earliest woman chief executive from the exchange a very high paid woman executive in Great Britain. P. Registration filings, World Economic Forum, [url=http://www.foxhuntersinn.co.uk/]polo ralph lauren uk[/url] the planet Book Encyclopedia.
Disgusted of Tunbridge Wells set in to have a treat. The muchloved Pantiles shopping centre during the Kentish spa town may be put up for sale more than by owner Jeremy Menuhin, pianist son of Americanborn musical legend Sir Yehudi Menuhin. Also on the block is a accompanying title Lord with the Manor of Rusthall.
A: It is a fact that dividing total cholesterol by HDL cholesterol provides for a number that yields valuable information in assessing the chance of cardiac event. In your husband's [url=http://www.mdjpatriotes.ca/]cheap moncler jacket[/url] case, the time is 2.19, plus it indicates the minimum risk to have a cardiac arrest. He doesn't have to give up foods he likes.
Valido per 30 giorni dal momento dell il bonus di benvenuto non l asso nella manica della sala di Titan, visto che la casino room propone anche [url=http://www.continyou.co.uk/]canada goose kensington parka[/url] un ottimo bonus settimanale ed un programma VIP tra i migliori in Italia. Casino certificato AAMS. Nonostante questo non sia sicuramente un punto a favore della sala, gli anni di esperienza maturati nel settore e la grande attenzione sempre dimostrata ai propri giocatori ci rende assolutamente sicuri che l di promozioni mozzafiato sia davvero dietro l REMOVED Whilliam Hill Casino Fondata nel 1934, William Hill diventata una delle [url=http://www.yaguar-network.fr/ralph-lauren-homme-pull-ralph-lauren-homme-c-6_48.html]pull ralph lauren[/url] [url=http://www.117start.nl/]canada goose online[/url] pi grandi organizzazioni nel settore delle scommesse sportive e dei giochi a distanza al mondo ed il number one britannico con circa 16,900 dipendenti e pi di 2,300 [url=http://www.responsiblegamblingns.ca/]canada goose montreal[/url] corner nel Regno Unito ed Irlanda.
http://www.responsiblegamblingns.ca/
[url=http://www.yaguar-network.fr/]ralph lauren pas cher[/url]
[url=http://www.nacelle-design.com/]ralph lauren polo[/url]
[url=http://www.foxhuntersinn.co.uk/]ralph lauren sale[/url]
[url=http://www.continyou.co.uk/]canada goose kensington parka[/url]
Post a Comment