[fpc-pascal] Portable coroutines

Mark Morgan Lloyd markMLl.fpc-pascal at telemetry.co.uk
Mon Mar 23 10:43:23 CET 2015


Michael Schnell wrote:
> On 03/20/2015 11:09 PM, Mark Morgan Lloyd wrote:
>> Efficient implementation of coroutines requires CPU-specific code in 
>> the RTL and possibly the compiler. However 
>> http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html suggests a 
>> way that coroutines can be implemented in a portable fashion in C, how 
>> can this be done in Object Pascal?
>>
> Lazarus seems to supports a similar concept by using events and 
> "Application.ProcessMessages". it might not be especially efficient, 
> though.

My tentative solution simplifies to the excerpt below, which I think is 
reasonably efficient.

..
     // Check that we're not trying to jump into exception blocks etc. Valid
     // line numbers are known to be > 0, the assertion is CPU-specific.

     if state.line > 0 then begin
       SetJmp(sanity);
       Assert(PtrUInt(state.env.sp) shr 1 xor PtrUInt(state.env.bp) =
                 PtrUInt(sanity.sp) shr 1 xor PtrUInt(sanity.bp),
                 'Bad stack frame at xfer to line ' + 
IntToStr(state.line - 1));
       LongJmp(state.env, state.line)
     end;

     if SetJmp(state.env) = 0 then begin
       state.line := StrToInt( (*$I %LINE% *) );
       exit('A')
     end;

     if SetJmp(state.env) = 0 then begin
..

Pity about the StrToInt(), which in principle could be resolved at 
compilation time.

-- 
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]



More information about the fpc-pascal mailing list