[fpc-pascal] Function reference doesn't capture in thread

Sven Barth pascaldragon at googlemail.com
Sat Sep 17 14:40:53 CEST 2022

Am 17.09.2022 um 07:02 schrieb Hairy Pixels via fpc-pascal:
> Can anyone explain why this program doesn’t capture the state of the local variable “I” and execute in order? It will return something like this:
> Invoked: 3 id: 00000001029D41C0
> Invoked: 0 id: 00000001029D42C0
> Invoked: 0 id: 00000001029D44C0
> Invoked: 0 id: 00000001029D43C0
> It works if you call Start directly before WaitFor, but why? I would expect the function reference to capture i, start the thread and then block the program after the sleep calls but instead the sleep calls appear to do nothing and the program exists immediately.

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.


More information about the fpc-pascal mailing list