C multithreading linux networks

I have a network application on the gateway. It receives and sends packets. For most of them, my gateway acts as a router, but in some cases it can also receive packets.

Should I:

  • only one main thread
  • main stream + send stream, responsible for its correct circulation of the stream
  • as many threads as there are threads
  • something else.

?

+4
source share
4 answers

Doing multithreading correctly is not just a question, in many cases select and friends will be much easier to create.

+2
source

Your case sounds like a typical Unix service daemon. A popular solution to your problem is not using threads, but plugs.

The idea is that your program is listening on a socket and waiting for connections. As soon as the connection comes, it forks. Then the child process continues to process the connection. The father’s process itself simply continues in a loop and waits for incoming connections.

Benefits for streaming:

  • Very simple program design.
  • No problem with concurrency
  • Installed Method for Unix / Linux Systems

Disadvantages:

  • Things get more complicated when multiple connections interact with each other (your use case is not like them)
  • Decreased performance on Windows systems (not Unix systems!)

You can find many sample code on the Internet.

+2
source

I know little about network applications, but I think it is:

  • If you have the ability to respond asynchronously to requests, you probably only use one thread (for example, in Node.JS). If you cannot respond asynchronously, the main thread will always block other actions.
  • If you cannot respond asynchronously to your requests, you need to use multiple threads. But you can achieve this in various ways: you can create a stream or a limited number of threads for each request and then assign them to your requests.
+1
source

My personal preference is to use one main thread and one worker thread for each connection. No cap. I assume that your server will be stateless, like an HTTP server.

For stateful servers, you will need to somehow determine the number of threads.

0
source

All Articles