r/cprogramming • u/SheikHunt • May 06 '26
Async/Await in C?
The question explains itself, but for context:
I am writing an Over-Engineered HTTP server for fun's and learning's sake, and I have hit a conceptual roadblock.
Currently, the server works thusly:
One (1) thread sits on a port and accept()s incoming requests and adds them to a queue, then pthread_cond_signal()s a condition that...
... Four (4) threads (request handlers) are pthread_cond_wait()ing on, one of whom will pick up the request and parse it.
Here comes the issue:
Similar to that the server simply adds each request to a queue, I want each request handler to, once it's parsed a request, hand it off to some HTTP_<method> function, then pick up the next request from the queue, only returning to the original point of execution (the point where HTTP_<method> was called), where it then returns a response.
The only two ways that comes to mind of doing this, one of them require N more threads sitting on another queue, which I feel weird about, and the other requires some Macro Fuckery that I found on a Github repository then lost, so Idk if it even is feasible.
How do I go forward from here?
TL;DR: Async Await for C; good, bad, or disgustingly ugly? Potential other solutions?
5
u/ChickenSpaceProgram May 06 '26
I would just pass a function pointer in that gets called whenever a request matches it. If the user thinks what they're doing is heavyweight enough, let them delegate it to a thread pool themselves inside the callback.
Another approach is to use something like FastCGI; either make your application a much-simpler FastCGI client and let NGINX handle all the HTTP stuff, or make your HTTP server handle client requests by delegating them to FastCGI clients.
3
u/Karyo_Ten May 06 '26
If you're doing over-engineering you might as well over-over-engineer and use continuations:
https://arxiv.org/pdf/1011.4558
Otherwise, if it's allowed to be non-portable, use llvm coroutines, co_await and friends.
3
u/mtimmermans May 07 '26
Async/await is just a compiler trick that rewrites your function into a state machine. In C, if you need a state machine then you should just write a state machine.
2
u/tchernobog84 May 07 '26
Use an event queue library such as libuv: https://libuv.org/
1
u/markand67 May 06 '26
Async/Await is usually implemented using coroutines. I've done that using minicoro
1
u/runningOverA May 07 '26
Using "processes" instead of threads will instantly solve all of these problems.
Unless :
- You are building it on Windows, then threads are the popular option.
- or you are short on memory and large on processors, like 64 cores each running a thread and you want to use a single code-data base to save on RAM.
1
u/kzrts May 07 '26
Are you not using epoll() for the queue ?