From 9ff00f18a38559f668cb5c27e6d814dddffa801d Mon Sep 17 00:00:00 2001 From: Garrett D'Amore Date: Fri, 23 Dec 2016 13:00:50 -0800 Subject: Add thread & condition variable checks to platform tests. --- tests/platform.c | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 1 deletion(-) (limited to 'tests/platform.c') diff --git a/tests/platform.c b/tests/platform.c index 85c7ba59..59d8cd6d 100644 --- a/tests/platform.c +++ b/tests/platform.c @@ -15,7 +15,9 @@ #include #endif -uint64_t getms(void) { +uint64_t +getms(void) +{ #ifdef _WIN32 return (GetTickCount()) ; #else @@ -37,6 +39,33 @@ uint64_t getms(void) { #endif } +// Add is for testing threads. +void +add(void *arg) +{ + *(int *)arg += 1; +} + +// Notify tests for verifying condvars. +struct notifyarg { + int did; + int when; + nni_mutex mx; + nni_cond cv; +}; + +void +notifyafter(void *arg) +{ + struct notifyarg *na = arg; + + nni_usleep(na->when); + nni_mutex_enter(&na->mx); + na->did = 1; + nni_cond_signal(&na->cv); + nni_mutex_exit(&na->mx); +} + TestMain("Platform Operations", { int rv = nni_init(); // This is required for anything else to work @@ -98,4 +127,64 @@ TestMain("Platform Operations", { nni_mutex_fini(&mx); }) }) + + Convey("Threads work", { + nni_thread *thr; + int val = 0; + int rv; + + Convey("We can create threads", { + rv = nni_thread_create(&thr, add, &val); + So(rv == 0); + So(thr != NULL); + + Convey("It ran", { + nni_usleep(50000); // for context switch + So(val == 1); + }) + Convey("We can reap it", { + nni_thread_reap(thr); + }) + }) + }) + Convey("Condition variables work", { + struct notifyarg arg; + nni_thread *thr = NULL; + + So(nni_mutex_init(&arg.mx) == 0); + So(nni_cond_init(&arg.cv, &arg.mx) == 0); + Reset({ + if (thr != NULL) { + nni_thread_reap(thr); + thr = NULL; + } + nni_cond_fini(&arg.cv); + nni_mutex_fini(&arg.mx); + }); + + Convey("Notification works", { + arg.did = 0; + arg.when = 10000; + So(nni_thread_create(&thr, notifyafter, &arg) == 0); + + nni_mutex_enter(&arg.mx); + if (!arg.did) { + nni_cond_wait(&arg.cv); + } + nni_mutex_exit(&arg.mx); + So(arg.did == 1); + }) + + Convey("Timeout works", { + arg.did = 0; + arg.when = 200000; + So(nni_thread_create(&thr, notifyafter, &arg) == 0); + nni_mutex_enter(&arg.mx); + if (!arg.did) { + nni_cond_waituntil(&arg.cv, nni_clock() + 10000); + } + So(arg.did == 0); + nni_mutex_exit(&arg.mx); + }) + }) }) \ No newline at end of file -- cgit v1.2.3-70-g09d2