Gorounte:
A goroutine is a lightweight thread managed by the Go runtime.
go f(x, y, z) starts a new goroutine running f(x, y, z)
The evaluation of
f
, x
, y
, and z
happens in the current goroutine and the execution of f
happens in the new goroutine. Goroutines run in the same address space, so access to shared memory must be synchronized.
Channels:
Channels are a typed conduit through which you can send and receive values with the channel operator,
<-
.
Channels must be created before use:
ch := make(chan int)
By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
Channels can be buffered. Provide the buffer length as the second argument to
make
to initialize a buffered channel:ch := make(chan int, 100)
Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.
A sender can
close
a channel to indicate that no more values will be sent. Only the sender should close a channel, never the receiver. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range
loop.
No comments:
Post a Comment