I want to extend an existing server written in C++ to be able to communicate with an other server over websockets (e.g. logging or user authorisation purposes). All examples (including the very well written Beej's Guide) I've found have an infinite loop (e.g. for, or while) to handle the socket's send and receive methods. The main problem with these examples (e.g. chat server/clients) is, that the servers are focussed on the sockets, which means that a server blocks during the send and receive process and is not available for any other operation.

Well therefore I thought that I may outsource the whole socket communication in an own thread and only call the send method from the main program, while the whole process of sending the request and wait for the answer is done inside the thread. When an answer from the other server arrives, the threads sends the information back to the main program, which validates and process the information. Because of my experience with node.js I would like to have a kind of a callback to process the answer in the main program (wouldn't that be easy?).

Besides my leak of knowledge how I can exchange data between the parent process and the threads (which was started already) I'm struggling to find an example, how you can avoid a socket to block the whole program, while the parent program can focus on other tasks and can use the socket in an "asynchronous" way. I'm sure that this is not an unusual problem and I would be glad if someone has an hint or idea.

My actuall idea is to use fork() for creating a child which handles all the I/O with sockets (then I dont care if it blocks) and use a pipe to async read and write between the parent and the child. But I'm still looking for a usefull example.

1 Answer 1


The blocking read is antiquated; modern servers use a asynchronous read where the program passes a buffer to the API where the data should end up in and gets a token representing the operation. No extra threads necessary.

Several token can be waited for at the same time so the server can dispatch a several reads and writes and then wait on all tokens until any finished and when one does use the token that woke up the thread to identify which operation succeeded and continue the work needed for that socket. (this is what node.js does behind the scenes).

Though your problem with the thread communicating is a producer/consumer problem, the main thread writing to each socket is a producer and each thread writing is a consumer. Each thread reading from the socket is a producer and the main thread waiting on the reads is a consumer.

  • Do you have an example of async I/O in C/C++ with sockets?
    – FredFloete
    Jul 13, 2015 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.