Functions and reentrancy

blomster
2008-10-08
2008-10-14
  • blomster - 2008-10-08

    I've been doing some plc coding for the first time (target is Indralogic/Codesys2/Codesys3). I have 30+ years of experience of other environments, and 30- days of Codesys.. so I'm worrying if I got this right:

    Writing a function doing math and geometry. Function will be called from different tasks, of different priorities, so it can be interrupted and another task might call the same function. Simplified could look like

    FUNCTION FUN_AngleFromPosition : REAL

    VAR_INPUT

    pos: UDINT;
    

    END_VAR

    VAR

    CosV: REAL;
    
    NewPos: REAL;
    
    y: REAL;
    

    END_VAR

    ... code code code...

    CosV := RodLength * RodLength /(RealStrokeL*y - ... code code
    
    FUN_AngleFromPosition := ACOS(CosV);
    

    Now other programmers warn me and say I must use a function block and instantiate it, otherwise result would be unreliable.

    I don't understand that. I would expect that the local variables, like CosV, would be on a stack somewhere, so that if a higher priority task calls same function it will have its own copy of CosV, so the lower priority task's copy would NOT be destroyed.

    I understand that if I compute and change global variables in a function that can be interrupted, it will introduce the same dangers as you find in a non thread-safe routine in Windows, for instance, unless I semaphore-protect it. (globals in my example are used, but they are only read, not written).

    But I see no such dangers in the above example?? I would expect the above to be safe. But if I'm wrong it will be terribly dangerous. So I ask if somebody who understands this would please confirm if it's OK, or warn me if it's wrong.

    Thanks!

    /Jens

     
  • deluxe79 - 2008-10-14

    Every task that calls the same function, makes its own instance of it on the heap. Therefore every variable defined in the function will remain private. Only when declaring an instance of a function block or variable globally(or in a PRG) that are shared by multiple tasks, the presentation of semaphore locks would be needed. And locks are only needed for task who are writing to the objects.

     
  • blomster - 2008-10-14

    Thank you Frank. I was hoping this was indeed so, but felt uncertain because I'm so unfamiliar with the inner workings of Codesys. Feel better now..

    /Jens

     

Log in to post a comment.