test: improve pthread test

This commit is contained in:
Bananymous 2025-05-05 19:21:47 +03:00
parent f14774d034
commit 2dc4733ac1
2 changed files with 45 additions and 11 deletions

View File

@ -5,6 +5,7 @@ set(USERSPACE_TESTS
test-mmap-shared
test-mouse
test-popen
test-pthread
test-setjmp
test-shared
test-sort

View File

@ -1,28 +1,61 @@
#include <stdio.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
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<int*>(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<int*>(value));
return 0;
}