SYNC Statement

Marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a block of statements, and then releasing the lock.

sync-statement

Example

class-id Account.
  working-storage section.    
  01 balance binary-long.
  01 r type Random value new Random.
  method-id new.
  procedure division using value init as binary-long.
      move init to balance
  end method.

  method-id Withdraw.
  procedure division using value amount as binary-long returning ret as binary-long.
  *> This condition will never be true unless the lock statement
  *> is commented out:
      if balance > 0
          display "< 0"
          raise new Exception("Negative Balance")
      end-if
      sync on self
          if balance >= amount
               display "In critical section"
               *>display "Balance before Withdrawal :  " balance
               *>display "Amount to Withdraw        : -" amount
               compute balance = balance - amount
               *>display "Balance after Withdrawal  :  " balance
               move amount to ret
          else          
               display "In critical section"
               move 0 to ret
          end-if
      end-sync
  end method.

  method-id DoTransactions.
  local-storage section.
  01 i binary-long.
  procedure division.
      perform varying i from 0 by 1 until i = 100
          invoke Withdraw(r::Next(1, 100))
      end-perform
  end method.
end class.