Do buffered channels maintain order?

“Are you guaranteed that B will read data In the same order that A put it into the channel?” Yes. The order of data is guaranteed. But the delivery is guaranteed only for unbuffered channels, not buffered. (see second section of this answer) You can see the idea of channels illustrated in “The Nature Of … Read more

What is channel buffer size?

The buffer size is the number of elements that can be sent to the channel without the send blocking. By default, a channel has a buffer size of 0 (you get this with make(chan int)). This means that every single send will block until another goroutine receives from the channel. A channel of buffer size … Read more

Closing channel of unknown length

Once a channel is closed, you can’t send further values on it else it panics. This is what you experience. This is because you start multiple goroutines that use the same channel and they send values on it. And you close the channel in each of it. And since they are not synchronized, once the … Read more

How to collect values from N goroutines executed in a specific order?

Goroutines run concurrently, independently, so without explicit synchronization you can’t predict execution and completion order. So as it is, you can’t pair returned numbers with the input numbers. You can either return more data (e.g. the input number and the output, wrapped in a struct for example), or pass pointers to the worker functions (launched … Read more

How to calculate the average rgb color values of a bitmap

The fastest way is by using unsafe code: BitmapData srcData = bm.LockBits( new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int stride = srcData.Stride; IntPtr Scan0 = srcData.Scan0; long[] totals = new long[] {0,0,0}; int width = bm.Width; int height = bm.Height; unsafe { byte* p = (byte*) (void*) Scan0; for (int y = 0; y … Read more