[fpc-devel] Possible idea... "safe" subroutines/methods

J. Gareth Moreton gareth at moreton-family.com
Fri May 3 19:37:46 CEST 2019


This is something I've been thinking about for a while, and I wonder how 
practical it is or if it's a good idea - the ability to mark specific 
routines as thread-safe with a directive named "safe" or "threadsafe".

By telling the compiler that the procedure (or maybe a whole class) is 
thread-safe, you are telling it that you can guarantee that any objects, 
fields or global variables that you access are guaranteed to not 
suddenly change mid-routine (because another thread has modified it).  
This would allow the compiler to move commonly-accessed fields into 
local registers or the stack for faster access, especially if the fields 
are only read and not written, since they'll be guaranteed to contain a 
constant value.

To give an example as to where this would be useful, my recent case 
refactoring patch - https://bugs.freepascal.org/view.php?id=35479 - the 
compiler would do the local storage automatically and hence I wouldn't 
need to write such code, which would probably count as a micro-optimisation.

Of course, by explicitly saying a procedure is thread-safe, the compiler 
can make no allowances when other threads actually do modify the value, 
potentially causing unpredictable behaviour, but because it's an 
explicit directive, the onus is on the programmer to ensure the routine 
is actually thread-safe.

For reasons of safety, the compiler should probably not consider values 
thread-safe across the boundary of a try...except or a try...finally 
block, not because of the risk of another thread modifying it, but 
because an interrupt might, caused by an exception.

There are still some things to work out, like how the compiler would 
handle a safe routine calling another routine (whether it's safe or not).

What are your thoughts?

Gareth aka. Kit


---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus




More information about the fpc-devel mailing list