threading/semaphore

Source   Edit  

Semaphore for Nim.

Example:

import threading/semaphore

import std / os

var arrived = createSemaphore(2)

proc worker(i: int) =
  echo i, " starts"
  wait arrived
  sleep 1
  echo i, " progresses"
  signal arrived

var threads: array[4, Thread[int]]
for i in 0..<4:
  createThread(threads[i], worker, i)
joinThreads(threads)

Types

Semaphore = object

A semaphore is a synchronization primitive that controls access to a shared resource through the use of a counter. If the counter is greater than zero, then access is allowed. If it is zero, then access is denied. What the access is depends on the use of the semaphore.

Semaphores are typically used to limit the number of threads than can access some (physical or logical) resource.

Semaphores are of two types: counting semaphores and binary semaphores. Counting semaphores can take non-negative integer values to indicate the number of units of a particular resource that are available. Binary semaphores can only take the values 0 and 1 and are used to implement locks.

Source   Edit  

Procs

proc `=copy`(dest: var Semaphore; src: Semaphore) {.error.}
Source   Edit  
proc `=destroy`(s: Semaphore) {.inline, ...raises: [], tags: [], forbids: [].}
Source   Edit  
proc `=sink`(dest: var Semaphore; src: Semaphore) {.error.}
Source   Edit  
proc createSemaphore(count: Natural = 0): Semaphore {....raises: [], tags: [],
    forbids: [].}
Source   Edit  
proc signal(s: var Semaphore) {.inline, ...raises: [], tags: [], forbids: [].}
Signal the semaphore. Source   Edit  
proc wait(s: var Semaphore) {....raises: [], tags: [], forbids: [].}
Wait for the semaphore to be signaled. If the semaphore's counter is zero, wait blocks until it becomes greater than zero. Source   Edit