threading/once

Search:
Group by:
Source   Edit  

Once for Nim.

Example:

import threading/once

type
  Singleton = object
    data: int

var
  counter = 1
  instance: ptr Singleton
  exceptionOccurred = false
  o = createOnce()

proc getInstance(): ptr Singleton =
  once(o):
    if not exceptionOccurred:
      # Simulate an exception on the first call
      exceptionOccurred = true
      raise newException(ValueError, "Simulated error")
    instance = createSharedU(Singleton)
    instance.data = counter
    inc counter
  result = instance

proc worker {.thread.} =
  try:
    for i in 1..1000:
      let inst = getInstance()
      assert inst.data == 1
  except ValueError:
    echo "Caught expected ValueError"

var threads: array[10, Thread[void]]
for i in 0..<10:
  createThread(threads[i], worker)
joinThreads(threads)
deallocShared(instance)
echo "All threads completed"

Types

Once = object
Once is a type that allows you to execute a block of code exactly once. The first call to once will execute the block of code and all other calls will be ignored. All concurrent calls to once are guaranteed to observe any side-effects made by the active call, with no additional synchronization. Source   Edit  

Procs

proc `=copy`(dest: var Once; source: Once) {.error.}
Source   Edit  
proc `=destroy`(o: Once) {.inline, ...raises: [], tags: [], forbids: [].}
Source   Edit  
proc `=sink`(dest: var Once; source: Once) {.error.}
Source   Edit  
proc createOnce(): Once {....raises: [], tags: [], forbids: [].}
Source   Edit  

Templates

template once(o: Once; body: untyped)
Executes body exactly once. Source   Edit