aboutsummaryrefslogtreecommitdiff
path: root/contrib
diff options
context:
space:
mode:
authorAndreas Fritiofson <andreas.fritiofson@gmail.com>2021-05-27 09:45:28 +0200
committerAntonio Borneo <borneo.antonio@gmail.com>2021-06-04 17:41:48 +0100
commit6b94d2983171b8421f841ecd0a4fd2d2aa98262e (patch)
tree4afe8055ae67ba6781aace162df08d8f9ac4618f /contrib
parent968f5082dd7304ba3d8f72f481f4f76886779ea9 (diff)
downloadriscv-openocd-6b94d2983171b8421f841ecd0a4fd2d2aa98262e.zip
riscv-openocd-6b94d2983171b8421f841ecd0a4fd2d2aa98262e.tar.gz
riscv-openocd-6b94d2983171b8421f841ecd0a4fd2d2aa98262e.tar.bz2
contrib: add an example of using list.h
Change-Id: Ic3d399d7ad2e4d10677cf78d64968040941b74e5 Signed-off-by: Andreas Fritiofson <andreas.fritiofson@gmail.com> Signed-off-by: Antonio Borneo <borneo.antonio@gmail.com> Reviewed-on: http://openocd.zylin.com/6280 Tested-by: jenkins Reviewed-by: Tim Newsome <tim@sifive.com>
Diffstat (limited to 'contrib')
-rw-r--r--contrib/list_example.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/contrib/list_example.c b/contrib/list_example.c
new file mode 100644
index 0000000..0f62b86
--- /dev/null
+++ b/contrib/list_example.c
@@ -0,0 +1,74 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/* Copyright (C) 2021 by Andreas Fritiofson <andreas.fritiofson@gmail.com> */
+
+/*
+ * Simple example of using a circular doubly linked list through list.h
+ *
+ * gcc -I ../src/ list_example.c -o list_example
+ */
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <assert.h>
+#include <helper/list.h>
+
+static LIST_HEAD(threads);
+
+struct thread {
+ int id;
+ uint64_t tcb_address;
+ struct list_head lh;
+};
+
+void insert(struct thread *t)
+{
+ list_add_tail(&t->lh, &threads);
+}
+
+void remove(struct thread *t)
+{
+ list_del(&t->lh);
+}
+
+struct thread *lookup_id(int id)
+{
+ struct thread *t;
+ list_for_each_entry(t, &threads, lh) {
+ if (t->id == id)
+ return t;
+ }
+ return NULL;
+}
+
+struct thread *lookup_tcb(uint64_t addr)
+{
+ struct thread *t;
+ list_for_each_entry(t, &threads, lh) {
+ if (t->tcb_address == addr)
+ return t;
+ }
+ return NULL;
+}
+
+int main(void)
+{
+ struct thread t1 = { .id = 1, .tcb_address = 111111111 };
+ struct thread t2 = { .id = 2, .tcb_address = 222222222 };
+ struct thread t3 = { .id = 3, .tcb_address = 333333333 };
+
+ insert(&t1);
+ insert(&t2);
+ assert(lookup_id(1) == &t1);
+ assert(lookup_tcb(111111111) == &t1);
+ assert(lookup_id(2) == &t2);
+ assert(lookup_id(42) == NULL);
+ remove(&t1);
+ assert(lookup_id(1) == NULL);
+ insert(&t3);
+ remove(&t2);
+ assert(lookup_id(3) == &t3);
+ assert(lookup_tcb(333333333) == &t3);
+ assert(lookup_id(2) == NULL);
+ remove(&t3);
+ assert(list_empty(&threads));
+}