[fpc-pascal] Function reference doesn't capture in thread
Hairy Pixels
genericptr at gmail.com
Sat Sep 17 16:38:20 CEST 2022
> On Sep 17, 2022, at 7:40 PM, Sven Barth <pascaldragon at googlemail.com> wrote:
>
> It seems you haven't read the part about capturing variables in my announcement mail, cause you have two problems:
> First the specific problem your code has: i is a global variables and global variables are *never* captured, because they don't need to.
> But even if you'd change your code so that the threads are initialized inside a procedure instead of the main block this would still not work, because variables are captured *by reference* which means that i would be shared between all newly created threads plus the main thread and depending on how the threads are scheduled the main thread will reach the call to WaitFor where i will again start from 0.
I didn’t know they were captured by reference! Does this mean they’re essentially pointers pointing the same variable?
Even so I’m trying now to modifying the example by copying to a local variable but I still see this same behavior suggesting there isn’t actually a copy. Why is this?
callback := TCallback.Create(procedure
var
index: integer;
begin
index := i;
writeln('Invoked: ', index, ' id: ', HexStr(TThread.CurrentThread));
end);
Regards,
Ryan Joseph
More information about the fpc-pascal
mailing list