From d3046284b23ca81be438c94e8f83b7e13e929d81 Mon Sep 17 00:00:00 2001 From: Nakidai Date: Sat, 28 Sep 2024 16:09:14 +0300 Subject: Make it multithreaded And also add `int n` to the CPTC_requestHandler so it threads will not conflict with each other with filenames --- cptc.c | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) (limited to 'cptc.c') diff --git a/cptc.c b/cptc.c index 0396b71..1dafddc 100644 --- a/cptc.c +++ b/cptc.c @@ -1,11 +1,14 @@ #include "cptc.h" +#include #include #include #include #include #include + +#include #include #include @@ -20,11 +23,30 @@ } while (0) \ +struct RequestHandlerArgs +{ + int fd; + int n; + bool accept; +}; + +static void *requestHandlerThread(struct RequestHandlerArgs *arg) +{ + int fd = arg->fd; + int n = arg->n; + arg->accept = true; + CPTC_requestHandler(fd, n); + close(fd); + pthread_exit(NULL); +} + + void CPTC(const char *ip, in_port_t port) { struct sockaddr_in addr, peer; socklen_t peer_size; int fd, peerfd; + int n = 0; curl_easy_init(); @@ -56,10 +78,10 @@ void CPTC(const char *ip, in_port_t port) } printf("Connection from %s:%u!\n", inet_ntoa(peer.sin_addr), peer.sin_port); - /* - * TODO: Make it multithreaded - */ - CPTC_requestHandler(peerfd); - close(peerfd); + pthread_t thread; + struct RequestHandlerArgs arg = {peerfd, n++, false}; + pthread_create(&thread, NULL, (void *(*)(void *))requestHandlerThread, &arg); + pthread_detach(thread); + while (!arg.accept); } } -- cgit 1.4.1