Concurrency is not Parallelism (2012)
Once we have the breakdown, parallelization can fall out and correctness is easy.
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
Once we have the breakdown, parallelization can fall out and correctness is easy.
In our book transport problem, substitute:
It becomes a concurrent design for a scalable web service.
Gophers serving web content.
Not the place for a tutorial, just quick highlights.
A goroutine is a function running independently in the same address space as other goroutines
f("hello", "world") // f runs; we wait
go f("hello", "world") // f starts running g() // does not wait for f to return
Like launching a function with shell's & notation.
(They're a bit like threads, but they're much cheaper.)
Goroutines are multiplexed onto OS threads as required.
When a goroutine blocks, that thread blocks but no other goroutine blocks.
Channels are typed values that allow goroutines to synchronize and exchange information.
timerChan := make(chan time.Time) go func() { time.Sleep(deltaT) timerChan <- time.Now() // send time on timerChan }() // Do something else; when ready, receive. // Receive will block until timerChan delivers. // Value sent is other goroutine's completion time. completedAt := <-timerChan
33
Select
The select statement is like a switch, but the decision is based on ability to communicate rather than equal values.
select { case v := <-ch1: fmt.Println("channel 1 sends", v) case v := <-ch2: fmt.Println("channel 2 sends", v) default: // optional fmt.Println("neither channel was ready") }
34
Go really supports concurrency
Really.
It's routine to create thousands of goroutines in one program.
(Once debugged a program after it had created 1.3 million.)
Stacks start small, but grow and shrink as required.
Goroutines aren't free, but they're very cheap.
Make some concurrent calculations easier to express.
They are just local functions.
Here's a non-concurrent example:
func Compose(f, g func(x float) float) func(x float) float { return func(x float) float { return f(g(x)) } }
print(Compose(sin, cos)(0.5))
36
Some examples
Learn concurrent Go by osmosis.
Use a closure to wrap a background operation.
This copies items from the input channel to the output channel:
go func() { // copy input to output for val := range input { output <- val } }()
The for range operation runs until channel is drained.
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。