sharedtables.nim 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Shared table support for Nim. Use plain old non GC'ed keys and values or
  10. ## you'll be in trouble. Uses a single lock to protect the table, lockfree
  11. ## implementations welcome but if lock contention is so high that you need a
  12. ## lockfree hash table, you're doing it wrong.
  13. ##
  14. ## Unstable API.
  15. import
  16. hashes, math, locks
  17. include "system/inclrtl"
  18. type
  19. KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B]
  20. KeyValuePairSeq[A, B] = ptr UncheckedArray[KeyValuePair[A, B]]
  21. SharedTable*[A, B] = object ## generic hash SharedTable
  22. data: KeyValuePairSeq[A, B]
  23. counter, dataLen: int
  24. lock: Lock
  25. template maxHash(t): untyped = t.dataLen-1
  26. include tableimpl
  27. template st_maybeRehashPutImpl(enlarge) {.dirty.} =
  28. if mustRehash(t.dataLen, t.counter):
  29. enlarge(t)
  30. index = rawGetKnownHC(t, key, hc)
  31. index = -1 - index # important to transform for mgetOrPutImpl
  32. rawInsert(t, t.data, key, val, hc, index)
  33. inc(t.counter)
  34. proc enlarge[A, B](t: var SharedTable[A, B]) =
  35. let oldSize = t.dataLen
  36. let size = oldSize * growthFactor
  37. var n = cast[KeyValuePairSeq[A, B]](allocShared0(
  38. sizeof(KeyValuePair[A, B]) * size))
  39. t.dataLen = size
  40. swap(t.data, n)
  41. for i in 0..<oldSize:
  42. let eh = n[i].hcode
  43. if isFilled(eh):
  44. var j: Hash = eh and maxHash(t)
  45. while isFilled(t.data[j].hcode):
  46. j = nextTry(j, maxHash(t))
  47. rawInsert(t, t.data, n[i].key, n[i].val, eh, j)
  48. deallocShared(n)
  49. template withLock(t, x: untyped) =
  50. acquire(t.lock)
  51. x
  52. release(t.lock)
  53. template withValue*[A, B](t: var SharedTable[A, B], key: A,
  54. value, body: untyped) =
  55. ## retrieves the value at ``t[key]``.
  56. ## `value` can be modified in the scope of the ``withValue`` call.
  57. ##
  58. ## .. code-block:: nim
  59. ##
  60. ## sharedTable.withValue(key, value) do:
  61. ## # block is executed only if ``key`` in ``t``
  62. ## # value is threadsafe in block
  63. ## value.name = "username"
  64. ## value.uid = 1000
  65. ##
  66. acquire(t.lock)
  67. try:
  68. var hc: Hash
  69. var index = rawGet(t, key, hc)
  70. let hasKey = index >= 0
  71. if hasKey:
  72. var value {.inject.} = addr(t.data[index].val)
  73. body
  74. finally:
  75. release(t.lock)
  76. template withValue*[A, B](t: var SharedTable[A, B], key: A,
  77. value, body1, body2: untyped) =
  78. ## retrieves the value at ``t[key]``.
  79. ## `value` can be modified in the scope of the ``withValue`` call.
  80. ##
  81. ## .. code-block:: nim
  82. ##
  83. ## sharedTable.withValue(key, value) do:
  84. ## # block is executed only if ``key`` in ``t``
  85. ## # value is threadsafe in block
  86. ## value.name = "username"
  87. ## value.uid = 1000
  88. ## do:
  89. ## # block is executed when ``key`` not in ``t``
  90. ## raise newException(KeyError, "Key not found")
  91. ##
  92. acquire(t.lock)
  93. try:
  94. var hc: Hash
  95. var index = rawGet(t, key, hc)
  96. let hasKey = index >= 0
  97. if hasKey:
  98. var value {.inject.} = addr(t.data[index].val)
  99. body1
  100. else:
  101. body2
  102. finally:
  103. release(t.lock)
  104. proc mget*[A, B](t: var SharedTable[A, B], key: A): var B =
  105. ## retrieves the value at ``t[key]``. The value can be modified.
  106. ## If `key` is not in `t`, the ``KeyError`` exception is raised.
  107. withLock t:
  108. var hc: Hash
  109. var index = rawGet(t, key, hc)
  110. let hasKey = index >= 0
  111. if hasKey: result = t.data[index].val
  112. if not hasKey:
  113. when compiles($key):
  114. raise newException(KeyError, "key not found: " & $key)
  115. else:
  116. raise newException(KeyError, "key not found")
  117. proc mgetOrPut*[A, B](t: var SharedTable[A, B], key: A, val: B): var B =
  118. ## retrieves value at ``t[key]`` or puts ``val`` if not present, either way
  119. ## returning a value which can be modified. **Note**: This is inherently
  120. ## unsafe in the context of multi-threading since it returns a pointer
  121. ## to ``B``.
  122. withLock t:
  123. mgetOrPutImpl(enlarge)
  124. proc hasKeyOrPut*[A, B](t: var SharedTable[A, B], key: A, val: B): bool =
  125. ## returns true iff `key` is in the table, otherwise inserts `value`.
  126. withLock t:
  127. hasKeyOrPutImpl(enlarge)
  128. proc withKey*[A, B](t: var SharedTable[A, B], key: A,
  129. mapper: proc(key: A, val: var B, pairExists: var bool)) =
  130. ## Computes a new mapping for the ``key`` with the specified ``mapper``
  131. ## procedure.
  132. ##
  133. ## The ``mapper`` takes 3 arguments:
  134. ##
  135. ## 1. ``key`` - the current key, if it exists, or the key passed to
  136. ## ``withKey`` otherwise;
  137. ## 2. ``val`` - the current value, if the key exists, or default value
  138. ## of the type otherwise;
  139. ## 3. ``pairExists`` - ``true`` if the key exists, ``false`` otherwise.
  140. ##
  141. ## The ``mapper`` can can modify ``val`` and ``pairExists`` values to change
  142. ## the mapping of the key or delete it from the table.
  143. ## When adding a value, make sure to set ``pairExists`` to ``true`` along
  144. ## with modifying the ``val``.
  145. ##
  146. ## The operation is performed atomically and other operations on the table
  147. ## will be blocked while the ``mapper`` is invoked, so it should be short and
  148. ## simple.
  149. ##
  150. ## Example usage:
  151. ##
  152. ## .. code-block:: nim
  153. ##
  154. ## # If value exists, decrement it.
  155. ## # If it becomes zero or less, delete the key
  156. ## t.withKey(1'i64) do (k: int64, v: var int, pairExists: var bool):
  157. ## if pairExists:
  158. ## dec v
  159. ## if v <= 0:
  160. ## pairExists = false
  161. withLock t:
  162. var hc: Hash
  163. var index = rawGet(t, key, hc)
  164. var pairExists = index >= 0
  165. if pairExists:
  166. mapper(t.data[index].key, t.data[index].val, pairExists)
  167. if not pairExists:
  168. delImplIdx(t, index)
  169. else:
  170. var val: B
  171. mapper(key, val, pairExists)
  172. if pairExists:
  173. st_maybeRehashPutImpl(enlarge)
  174. proc `[]=`*[A, B](t: var SharedTable[A, B], key: A, val: B) =
  175. ## puts a (key, value)-pair into `t`.
  176. withLock t:
  177. putImpl(enlarge)
  178. proc add*[A, B](t: var SharedTable[A, B], key: A, val: B) =
  179. ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
  180. ## This can introduce duplicate keys into the table!
  181. withLock t:
  182. addImpl(enlarge)
  183. proc del*[A, B](t: var SharedTable[A, B], key: A) =
  184. ## deletes `key` from hash table `t`.
  185. withLock t:
  186. delImpl()
  187. proc len*[A, B](t: var SharedTable[A, B]): int =
  188. ## number of elements in `t`
  189. withLock t:
  190. result = t.counter
  191. proc init*[A, B](t: var SharedTable[A, B], initialSize = 64) =
  192. ## creates a new hash table that is empty.
  193. ##
  194. ## This proc must be called before any other usage of `t`.
  195. ##
  196. ## `initialSize` needs to be a power of two. If you need to accept runtime
  197. ## values for this you could use the ``nextPowerOfTwo`` proc from the
  198. ## `math <math.html>`_ module or the ``rightSize`` proc from this module.
  199. assert isPowerOfTwo(initialSize)
  200. t.counter = 0
  201. t.dataLen = initialSize
  202. t.data = cast[KeyValuePairSeq[A, B]](allocShared0(
  203. sizeof(KeyValuePair[A, B]) * initialSize))
  204. initLock t.lock
  205. proc deinitSharedTable*[A, B](t: var SharedTable[A, B]) =
  206. deallocShared(t.data)
  207. deinitLock t.lock
  208. proc initSharedTable*[A, B](initialSize = 64): SharedTable[A, B] {.deprecated:
  209. "use 'init' instead".} =
  210. ## This is not posix compliant, may introduce undefined behavior.
  211. assert isPowerOfTwo(initialSize)
  212. result.counter = 0
  213. result.dataLen = initialSize
  214. result.data = cast[KeyValuePairSeq[A, B]](allocShared0(
  215. sizeof(KeyValuePair[A, B]) * initialSize))
  216. initLock result.lock