From 2dc4733ac15e56bd3318522d93126b1fe1261dbe Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 5 May 2025 19:21:47 +0300 Subject: [PATCH] test: improve pthread test --- userspace/tests/CMakeLists.txt | 1 + userspace/tests/test-pthread/main.cpp | 55 +++++++++++++++++++++------ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/userspace/tests/CMakeLists.txt b/userspace/tests/CMakeLists.txt index 26a8912f..a572bd1a 100644 --- a/userspace/tests/CMakeLists.txt +++ b/userspace/tests/CMakeLists.txt @@ -5,6 +5,7 @@ set(USERSPACE_TESTS test-mmap-shared test-mouse test-popen + test-pthread test-setjmp test-shared test-sort diff --git a/userspace/tests/test-pthread/main.cpp b/userspace/tests/test-pthread/main.cpp index 53562070..68dd342b 100644 --- a/userspace/tests/test-pthread/main.cpp +++ b/userspace/tests/test-pthread/main.cpp @@ -1,28 +1,61 @@ -#include #include +#include +#include #include +pthread_spinlock_t spinlock; + void* thread_func(void*) { - printf("hello from thread\n"); - return nullptr; + printf("[THREAD] locking spinlock\n"); + pthread_spin_lock(&spinlock); + printf("[THREAD] got spinlock\n"); + + sleep(1); + + printf("[THREAD] releasing spinlock\n"); + pthread_spin_unlock(&spinlock); + + int* value = static_cast(malloc(sizeof(int))); + if (value == nullptr) + { + perror("malloc"); + return nullptr; + } + + *value = 69; + + printf("[THREAD] exiting with %d\n", *value); + + return value; } int main(int argc, char** argv) { - pthread_t tid; + pthread_spin_init(&spinlock, 0); - printf("creating thread\n"); + printf("[MAIN] locking spinlock\n"); + pthread_spin_lock(&spinlock); - if (pthread_create(&tid, nullptr, &thread_func, nullptr) == -1) - { - perror("pthread_create"); - return 1; - } + printf("[MAIN] creating thread\n"); + + pthread_t thread; + pthread_create(&thread, nullptr, &thread_func, nullptr); sleep(1); - printf("exiting\n"); + printf("[MAIN] releasing spinlock\n"); + pthread_spin_unlock(&spinlock); + + printf("[MAIN] joining thread\n"); + + void* value; + pthread_join(thread, &value); + + if (value == nullptr) + printf("[MAIN] thread returned NULL\n"); + else + printf("[MAIN] thread returned %d\n", *static_cast(value)); return 0; }