1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 03:37:45 +00:00

Tests/Kernel: Properly synchronize threads in TestTCPSocket

We should wait for a server thread to actually listen(2) a server socket
before trying to connect to it. This hopefully should make the test less
flaky.
This commit is contained in:
Dan Klishch 2024-01-29 19:48:51 -05:00 committed by Andrew Kaster
parent e981197ee3
commit 4330cdee74

View file

@ -9,11 +9,12 @@
#include <LibTest/TestCase.h> #include <LibTest/TestCase.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <pthread.h> #include <pthread.h>
#include <semaphore.h>
#include <sys/socket.h> #include <sys/socket.h>
static constexpr u16 port = 1337; static constexpr u16 port = 1337;
static void* server_handler(void*) static void* server_handler(void* accept_semaphore)
{ {
int server_fd = socket(AF_INET, SOCK_STREAM, 0); int server_fd = socket(AF_INET, SOCK_STREAM, 0);
EXPECT(server_fd >= 0); EXPECT(server_fd >= 0);
@ -28,6 +29,9 @@ static void* server_handler(void*)
rc = listen(server_fd, 1); rc = listen(server_fd, 1);
EXPECT_EQ(rc, 0); EXPECT_EQ(rc, 0);
rc = sem_post(reinterpret_cast<sem_t*>(accept_semaphore));
VERIFY(rc == 0);
int client_fd = accept(server_fd, nullptr, nullptr); int client_fd = accept(server_fd, nullptr, nullptr);
EXPECT(client_fd >= 0); EXPECT(client_fd >= 0);
@ -49,8 +53,16 @@ static void* server_handler(void*)
static pthread_t start_tcp_server() static pthread_t start_tcp_server()
{ {
pthread_t thread; pthread_t thread;
int rc = pthread_create(&thread, nullptr, server_handler, nullptr); sem_t accept_semaphore;
EXPECT_EQ(rc, 0);
int rc = sem_init(&accept_semaphore, 0, 0);
VERIFY(rc == 0);
rc = pthread_create(&thread, nullptr, server_handler, &accept_semaphore);
VERIFY(rc == 0);
rc = sem_wait(&accept_semaphore);
VERIFY(rc == 0);
rc = sem_destroy(&accept_semaphore);
VERIFY(rc == 0);
return thread; return thread;
} }