Skip to content

Instantly share code, notes, and snippets.

@cheatfate
Created March 27, 2016 12:31
#
#
# Nim's Runtime Library
# (c) Copyright 2016 Nim Developers
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
import strutils
#const MultiThreaded = compileOption("threads")
const MultiThreaded = false
when MultiThreaded:
import locks
const
elementsPerNode = 64
when MultiThreaded:
type
ListNode[T] = ref object
next: ListNode[T]
d: array[elementsPerNode, T]
Queue*[T] = object
head, tail: ListNode[T]
hindex, tindex: int
hlock, tlock: Lock
else:
type
ListNode[T] = ptr object
next: ListNode[T]
d: array[elementsPerNode, T]
Queue*[T] = object
head, tail: ListNode[T]
hindex, tindex: int
proc newListNode[T](): ListNode[T] =
new(result)
proc initQueue*[T](): Queue[T] =
when MultiThreaded:
var node: ListNode[T]
result.head = cast[type node](allocShared0(sizeof(node[])))
result.tail = cast[type node](allocShared0(sizeof(node[])))
result.hindex = 0
result.tindex = 0
initLock result.hLock
initLock result.tLock
else:
result.head = newListNode[T]()
result.tail = newListNode[T]()
result.hindex = 0
result.tindex = 0
proc push*[T](q: Queue[T], v: var T) =
when MultiThreaded:
acquire q.lock
try:
discard
finally:
when MultiThreaded:
release g.lock
else:
discard
proc pop*[T](q: Queue[T], v: var T) =
when MultiThreaded:
acquire q.lock
try:
discard
finally:
when MultiThreaded:
release g.lock
else:
discard
type
testobj = object
field1: int
field2: int
var q = initQueue[testobj]()
echo(repr(q))
# queue.nim(88, 18) template/generic instantiation from here
# queue.nim(54, 33) template/generic instantiation from here
# queue.nim(42, 6) Error: type mismatch: got (ListNode[queue.testobj])
# but expected one of:
# system.new(a: var ref T)
# system.new(a: var ref T, finalizer: proc (x: ref T))
# system.new(T: typedesc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment