I saw an example in [vlang](https://vlang.io/compare), which use a special 
keyword **lock** to lock a block of code. And I want to implement it (let's 
call it lockBlock) in nim. Ideally, it should be something like
    
    
    var val = 0
    proc run() =
      lockBlock:
        var n = val
        for i in ..10000:
          n += 1 - 2*(i mod 2) # what is doing here does not mater
        val = n
    
    for i in 1..8: spawn run()
    sync()
    
    echo val  # correct output should be 8
    
    
    Run

I tried the following implementation of lockBlock, but it didn't work
    
    
    import locks, threadpool
    
    template lockBlock(code: untyped): untyped =
      var lock {.global.} : Lock  # declare to globals
      
      # template local variable for one time initialization
      var uninitialized = true
      if uninitialized:
        uninitialized = false
        initLock(lock)
      
      # copy withLock implementation
      block:
        acquire(lock)
        defer:
          release(lock)
        {.locks: [lock].}:
          code
    
    
    Run

How can I make the above code work ??

FYI, a program that have the same effect with explicit declaration of a lock
    
    
    import locks, threadpool
    
    var valLock : Lock
    initLock(valLock)
    
    var val = 0
    proc run() =
      withLock valLock:
        var n = val
        for i in ..10000:
          n += 1 - 2*(i mod 2)
        val = n
    
    for i in 1..8: spawn run()
    sync()
    
    echo val  # output 8
    
    
    Run

Reply via email to