Shop OBEX P1 Docs P2 Docs Learn Events
counting semaphore? — Parallax Forums

counting semaphore?

sssidneysssidney Posts: 64
edited 2010-08-12 10:22 in Propeller 1
I’m trying to implement a counting semaphore to periodically synch 2 cogs.

The main routine launches the code into the cogs that is basically doing this:
VAR
  long semCount

CON
  SEM_COUNT_LIMIT = 2

PUB testCog1
  repeat
     'do something useful here

     ' counting semaphore or race condition?
     semCount += 1
     repeat until ((semCount // SEM_COUNT_LIMIT) == 0)     

PUB testCog2
  repeat
     'do something useful too.

     ' counting semaphore or race condition?
     semCount += 1
     repeat until ((semCount // SEM_COUNT_LIMIT) == 0)     


So does this mechanism work or is this a race condition?

Comments

  • John AbshierJohn Abshier Posts: 1,116
    edited 2010-08-12 07:21
    I think it will work if you initialize semCount to -1.

    John Abshier
  • Heater.Heater. Posts: 21,230
    edited 2010-08-12 07:26
    Race condition.

    Why not just have a flag?

    1) When true testCog1 runs. testCog1 sets the flag false after whatever number of iterations. Then waits for the flag to go true again.

    2) When false testCog2 runs. testCog2 sets the flag true after whatever number of iterations. Then waits for the flag to go false again.

    I use this all the time. As long as there are only two cogs in the game it works fine.
  • sssidneysssidney Posts: 64
    edited 2010-08-12 07:36
    I don't think I properly explained what I'm trying to do. I need both cogs to do their own "do something useful here" code section simultaneously but then periodically synch up/wait for the other in the semaphore section. I guess what I’m looking to do is called a rendezvous i.e. the two cogs rendezvous at a point of execution in their respective routines, and neither is allowed to proceed until both have arrived. I don't think a flag will coordinate this - instead it will make the 2 cogs take turns running.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2010-08-12 09:58
    Two processes having write access to a single counter can lead to trouble. Use two counters, each owned by a process. Then for each process:
    repeat
      'do stuff
      mycount++
      repeat while (mycount - othercount > 0)
    
    BTW, the counters (both have to be longs) will eventually roll over. That's why the test condition cannot be mycount > othercount.

    -Phil
  • sssidneysssidney Posts: 64
    edited 2010-08-12 10:22
    That makes sense. Avoids multiple writers. Thanks!!!
Sign In or Register to comment.