Semaphore

Romuald
2010-07-05
2010-07-06
  • Romuald - 2010-07-05

    Hi,

    I need to use a semaphore to protect a global variable between several tasks. CoDeSys says that the FB SEMA is interruptable ! So if it is the case, is it reliable ?

    Below a small program that would tend to prove that it is not reliable:

    VAR_GLOBAL
    Β  gSema: SEMA;
    Β  gVar: DWORD;
    END_VAR
    
    PROGRAM TASK1
    VAR
    Β  var1: DWORD;
    END_VAR
    gSema(CLAIM := TRUE, RELEASE := FALSE);
    IF NOT gSema.BUSY THEN
    Β  var1 := var1 + 1;
    Β  gVar := gVar1 + 1;
    Β  gSema(CLAIM := FALSE, RELEASE := TRUE);
    END_IF
    
    PROGRAM TASK2
    VAR
    Β  var2: DWORD;
    END_VAR
    gSema(CLAIM := TRUE, RELEASE := FALSE);
    IF NOT gSema.BUSY THEN
    Β  var2 := var2 + 1;
    Β  gVar := gVar1 + 1;
    Β  gSema(CLAIM := FALSE, RELEASE := TRUE);
    END_IF
    

    After a time, gSema.BUSY is TRUE in the two tasks !

    So what real alternatives I have to protect the variable ?

    Thanks for your help,

    Romuald.

     
  • Romuald - 2010-07-06

    In fact there is a library more reliable for semaphores : SysLibSem.lib

     

Log in to post a comment.