aboutsummaryrefslogtreecommitdiff
path: root/src/pkg/runtime/lfstack.c
diff options
context:
space:
mode:
authorDmitriy Vyukov <dvyukov@google.com>2012-04-12 11:49:25 +0400
committerDmitriy Vyukov <dvyukov@google.com>2012-04-12 11:49:25 +0400
commita5dc7793c0fba8d6c81098248a4fc2e8b0ddad34 (patch)
tree9b2d1479d8c9ec3e79c9effceadf9bbef152a216 /src/pkg/runtime/lfstack.c
parent2d0d3d8f9efadcad71537b046e31f45a4b0a7844 (diff)
downloadgo-a5dc7793c0fba8d6c81098248a4fc2e8b0ddad34.tar.xz
runtime: add lock-free stack
This is factored out part of the: https://golang.org/cl/5279048/ (parallel GC) R=golang-dev, rsc CC=golang-dev https://golang.org/cl/5993043
Diffstat (limited to 'src/pkg/runtime/lfstack.c')
-rw-r--r--src/pkg/runtime/lfstack.c64
1 files changed, 64 insertions, 0 deletions
diff --git a/src/pkg/runtime/lfstack.c b/src/pkg/runtime/lfstack.c
new file mode 100644
index 0000000000..e4ea6e83da
--- /dev/null
+++ b/src/pkg/runtime/lfstack.c
@@ -0,0 +1,64 @@
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Lock-free stack.
+
+#include "runtime.h"
+#include "arch_GOARCH.h"
+
+#ifdef _64BIT
+// Amd64 uses 48-bit virtual addresses, 47-th bit is used as kernel/user flag.
+// So we use 17msb of pointers as ABA counter.
+# define PTR_BITS 47
+#else
+# define PTR_BITS 32
+#endif
+#define PTR_MASK ((1ull<<PTR_BITS)-1)
+
+void
+runtime·lfstackpush(uint64 *head, LFNode *node)
+{
+ uint64 old, new;
+
+ if((uint64)node != ((uint64)node&PTR_MASK)) {
+ runtime·printf("p=%p\n", node);
+ runtime·throw("runtime·lfstackpush: invalid pointer");
+ }
+
+ node->pushcnt++;
+ new = (uint64)node|(((uint64)node->pushcnt)<<PTR_BITS);
+ old = runtime·atomicload64(head);
+ for(;;) {
+ node->next = (LFNode*)(old&PTR_MASK);
+ if(runtime·cas64(head, &old, new))
+ break;
+ }
+}
+
+LFNode*
+runtime·lfstackpop(uint64 *head)
+{
+ LFNode *node, *node2;
+ uint64 old, new;
+
+ old = runtime·atomicload64(head);
+ for(;;) {
+ if(old == 0)
+ return nil;
+ node = (LFNode*)(old&PTR_MASK);
+ node2 = runtime·atomicloadp(&node->next);
+ new = 0;
+ if(node2 != nil)
+ new = (uint64)node2|(((uint64)node2->pushcnt)<<PTR_BITS);
+ if(runtime·cas64(head, &old, new))
+ return node;
+ }
+}
+
+void
+runtime·lfstackpop2(uint64 *head, LFNode *node)
+{
+ node = runtime·lfstackpop(head);
+ FLUSH(&node);
+}