1 /* <lambda>null2 * Copyright 2017-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.atomicfu.test 6 7 import kotlinx.atomicfu.* 8 import kotlin.test.* 9 10 class LockFreeQueueTest { 11 @Test 12 fun testBasic() { 13 val q = LockFreeQueue() 14 check(q.dequeue() == -1) 15 q.enqueue(42) 16 check(q.dequeue() == 42) 17 check(q.dequeue() == -1) 18 q.enqueue(1) 19 q.enqueue(2) 20 check(q.dequeue() == 1) 21 check(q.dequeue() == 2) 22 check(q.dequeue() == -1) 23 } 24 } 25 26 // MS-queue 27 public class LockFreeQueue { 28 private val head = atomic(Node(0)) 29 private val tail = atomic(head.value) 30 31 private class Node(val value: Int) { 32 val next = atomic<Node?>(null) 33 } 34 enqueuenull35 public fun enqueue(value: Int) { 36 val node = Node(value) 37 tail.loop { curTail -> 38 val curNext = curTail.next.value 39 if (curNext != null) { 40 tail.compareAndSet(curTail, curNext) 41 return@loop 42 } 43 if (curTail.next.compareAndSet(null, node)) { 44 tail.compareAndSet(curTail, node) 45 return 46 } 47 } 48 } 49 dequeuenull50 public fun dequeue(): Int { 51 head.loop { curHead -> 52 val next = curHead.next.value ?: return -1 53 if (head.compareAndSet(curHead, next)) return next.value 54 } 55 } 56 }