parent
c5cf21c0c4
commit
c51680e701
2 changed files with 47 additions and 13 deletions
|
|
@ -35,8 +35,10 @@ template withLock(t, x: untyped) =
|
||||||
release(t.lock)
|
release(t.lock)
|
||||||
|
|
||||||
proc iterAndMutate*[A](x: var SharedList[A]; action: proc(x: A): bool) =
|
proc iterAndMutate*[A](x: var SharedList[A]; action: proc(x: A): bool) =
|
||||||
## iterates over the list. If 'action' returns true, the
|
## Iterates over the list. If 'action' returns true, the
|
||||||
## current item is removed from the list.
|
## current item is removed from the list.
|
||||||
|
##
|
||||||
|
## .. warning:: It may not preserve the element order after some modifications.
|
||||||
withLock(x):
|
withLock(x):
|
||||||
var n = x.head
|
var n = x.head
|
||||||
while n != nil:
|
while n != nil:
|
||||||
|
|
@ -47,8 +49,9 @@ proc iterAndMutate*[A](x: var SharedList[A]; action: proc(x: A): bool) =
|
||||||
if action(n.d[i]):
|
if action(n.d[i]):
|
||||||
acquire(x.lock)
|
acquire(x.lock)
|
||||||
let t = x.tail
|
let t = x.tail
|
||||||
|
dec t.dataLen # TODO considering t.dataLen == 0,
|
||||||
|
# probably the module should be refactored using doubly linked lists
|
||||||
n.d[i] = t.d[t.dataLen]
|
n.d[i] = t.d[t.dataLen]
|
||||||
dec t.dataLen
|
|
||||||
else:
|
else:
|
||||||
acquire(x.lock)
|
acquire(x.lock)
|
||||||
inc i
|
inc i
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,48 @@
|
||||||
import sharedlist
|
discard """
|
||||||
|
matrix: "--threads:on"
|
||||||
|
"""
|
||||||
|
|
||||||
var
|
import std/sharedlist
|
||||||
list: SharedList[int]
|
|
||||||
count: int
|
|
||||||
|
|
||||||
init(list)
|
block:
|
||||||
|
var
|
||||||
|
list: SharedList[int]
|
||||||
|
count: int
|
||||||
|
|
||||||
for i in 1 .. 250:
|
init(list)
|
||||||
list.add i
|
|
||||||
|
|
||||||
for i in list:
|
for i in 1 .. 250:
|
||||||
inc count
|
list.add i
|
||||||
|
|
||||||
doAssert count == 250
|
for i in list:
|
||||||
|
inc count
|
||||||
|
|
||||||
deinitSharedList(list)
|
doAssert count == 250
|
||||||
|
|
||||||
|
deinitSharedList(list)
|
||||||
|
|
||||||
|
|
||||||
|
block: # bug #17696
|
||||||
|
var keysList = SharedList[string]()
|
||||||
|
init(keysList)
|
||||||
|
|
||||||
|
keysList.add("a")
|
||||||
|
keysList.add("b")
|
||||||
|
keysList.add("c")
|
||||||
|
keysList.add("d")
|
||||||
|
keysList.add("e")
|
||||||
|
keysList.add("f")
|
||||||
|
|
||||||
|
|
||||||
|
# Remove element "b" and "d" from the list.
|
||||||
|
keysList.iterAndMutate(proc (key: string): bool =
|
||||||
|
if key == "b" or key == "d": # remove only "b" and "d"
|
||||||
|
return true
|
||||||
|
return false
|
||||||
|
)
|
||||||
|
|
||||||
|
var results: seq[string]
|
||||||
|
for key in keysList.items:
|
||||||
|
results.add key
|
||||||
|
|
||||||
|
doAssert results == @["a", "f", "c", "e"]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue