On 5/6/20 2:29 PM, drug wrote:
06.05.2020 16:57, Steven Schveighoffer пишет:
```
foreach(i; 0..n) // instead of for(long i = 0; i < n;)
```
I guess that `proc` delegate cant capture `i` var of `foreach` loop
so the range violation doesn't happen.
foreach over a range of integers is lowered to an equivalent for loop,
so that was not the problem.
I was surprised but `foreach` version do not have range violation, so
there is difference between `foreach` and `for` loops. I did not try
DerivedThread at all, only suggested them to avoid var capture. I just
changed `for` by `foreach` and range violation gone. Probably this is
implementation details.
Ah yes, because foreach(i; 0 .. n) actually uses a hidden variable to
iterate, and assigns it to i each time through the loop. It used to just
use i for iteration, but then you could play tricks by adjusting i.
So the equivalent for loop would be:
for(int _i = 0; _i < n; ++_i)
{
auto i = _i; // this won't be executed after _i is out of range
... // foreach body
}
So the problem would not be a range error, but just random i's coming
through to the various threads ;)
Very interesting!
-Steve