Is Go a buffer channel without blocking?

A buffering channel is essentially a thread-safe FIFO queue. (See Is it possible to use the Go buffer channel as a thread-safe queue? )

I wonder how this is implemented. Is it blocked as described in Is there such a thing as a blocked queue for multiple read or write streams? ?

greping in the Go src directory ( grep -r Lock .|grep chan ) gives the following result:

 ./pkg/runtime/chan.c: Lock; ./pkg/runtime/chan_test.go: m.Lock() ./pkg/runtime/chan_test.go: m.Lock() // wait ./pkg/sync/cond.go: L Locker // held while observing or changing the condition 

Do not block my car (MacOS, intel x86_64). Is there an official resource to confirm this?

+6
source share
2 answers

If you read the runtime·chansend in chan.c , you will see that before checking, runtime·lock is called to check if the if(c->dataqsiz > 0) channel is buffered if(c->dataqsiz > 0) .

In other words, buffered channels (and all channels in general) use locks.

The reason your search did not find that you were looking for a “lock” with capital L. The lock function used for channels is the unexported C. function at run time.

+6
source

You can write without blocking (and even without waiting!) Implementations for everything that you like. Modern hardware primitives, such as CMPXCHG, are sufficient for universal use. But writing and testing such algorithms is not one of the simplest tasks. In addition to this, much faster algorithms can exist: blocking algorithms are just a very small subset of algorithms in general.

As far as I remember, Dmitry Vyukov wrote for Go in the past an unplanned implementation of the MPMC (mutli-producer / multi-user) channel, but the patch was left due to some problems with the Go select operator. Supporting this statement effectively seems very difficult.

The main goal of the Go channel type, however, is to provide a high-level concurrency primitive that can easily be used for a wide range of problems. Even developers who are not experts in parallel programming should be able to write the right programs, which can be easily analyzed and stored in large software projects. If you are interested in squeezing all the last bits of performance, you will have to write a custom implementation of the queue that suits your needs.

+4
source

All Articles