threading/rwlock

Source   Edit  

Readers-writer lock for Nim.

Example:

import threading/rwlock

import std / os

var rw = createRwLock()
var data = 0

proc worker =
  for i in 0..<100:
    writeWith rw:
      let tmp = data
      data = -1
      sleep 1
      data = tmp + 1

var threads: array[10, Thread[void]]
for i in 0..<10:
  createThread(threads[i], worker)
for i in 0..<100:
  readWith(rw, assert data >= 0)
joinThreads(threads)
assert data == 1000

Types

RwLock = object
Readers-writer lock. Multiple readers can acquire the lock at the same time, but only one writer can acquire the lock at a time. Source   Edit  

Procs

proc `=copy`(dest: var RwLock; source: RwLock) {.error.}
Source   Edit  
proc `=destroy`(rw: RwLock) {.inline, ...raises: [], tags: [], forbids: [].}
Source   Edit  
proc `=sink`(dest: var RwLock; source: RwLock) {.error.}
Source   Edit  
proc beginRead(rw: var RwLock) {....raises: [], tags: [], forbids: [].}
Acquire a read lock. Source   Edit  
proc beginWrite(rw: var RwLock) {....raises: [], tags: [], forbids: [].}
Acquire a write lock. Source   Edit  
proc createRwLock(): RwLock {....raises: [], tags: [], forbids: [].}
Source   Edit  
proc endRead(rw: var RwLock) {.inline, ...raises: [], tags: [], forbids: [].}
Release a read lock. Source   Edit  
proc endWrite(rw: var RwLock) {.inline, ...raises: [], tags: [], forbids: [].}
Release a write lock. Source   Edit  

Templates

template readWith(a: RwLock; body: untyped)
Acquire a read lock and execute body. Release the lock afterwards. Source   Edit  
template writeWith(a: RwLock; body: untyped)
Acquire a write lock and execute body. Release the lock afterwards. Source   Edit