4 ms·
I'm a bit confused: I see several threads running aparent infite loops generating numbers. It doesn't seem to be lazily evaluated (or is it?). Is this going to
by lt 17y ago
I'm a bit confused: I see several threads running aparent infite loops generating numbers. It doesn't seem to be lazily evaluated (or is it?). Is this going to run until it runs out of memory (or thread handles)?
When it runs, it is going to spawn a thread generating a sequence of numbers, then another one taking that sequence, start generating a new sequence based on that skipping multiples of a particular number, then start another one doing the same. Number of threads seems to always go up. Is that the right analysis of the code? Doesn't seem right to me.
- dadkins 17y agoYes, it's lazy. The sieve outputs on a channel, which blocks until you read it. It will only generate more numbers as they're consumed. Same thing with the filters.
- grogers 17y agoThis is because the default 'make(chan int)' creates a synchronous channel
- vito 17y agoThat blew my mind for a bit too. It's not lazy in the sense of postponing evaluation, it just blocks until something reads or writes from the channel. This could go on forever assuming you have something that reads from the channel in an infinite loop (as it looks like it's doing in main(), actually...), but the generators themselves only loop when the channel is interacted with.
- lt 17y agoIt does make more sense after understanding that. There's still the ever-increasing number of concurrent goroutines, but what just helped me accept that a bit is the fact is that each goroutine does not necessarily map to one thread (it actually does in one of their compilers - there's two - but that's an implementation detail).
- jacquesm 17y agoIt's like a 'generator' in many other languages. As soon as it has produced a result it will wait for the consumer to catch up, then generate another result and so on.