DEV Community

UlafBogor
UlafBogor

Posted on

I try to create a C++ program that receives data and continuously process it, is it required that I use async/threading?

I created a Websocket server in Python that receives data (maximum 300 bytes) from a browser, and in python when creating server/client you always use asyncio or threading, so you would be able to listen continuously while at the same time data is processed or handling other clients.

My question is it required in C++ too?
I try to make the C++ program get this data, process it, and store it, do I need to use multithreading/async for it too?

Bonus question
I on the fence between setting a separate python socket server and a socket C++ client to send the data
Or using shared memories

I was told shared memories is harder, and is more for if I need to share a lot of data very fast
But still want your opinion

Top comments (1)

Collapse
 
dmitry_labintcev_9e611e04 profile image
Dmitry Labintcev

Short answer: No, threading/async is not strictly required, but it depends on your use case.

When you DON'T need threading

If you have a simple scenario with:

  • One client at a time
  • Fast processing (< 1ms)
  • No strict real-time requirements

A simple blocking loop works fine:

while (true) {
    int bytes = recv(socket, buffer, 300, 0);  // blocks here
    process(buffer);  // process while not receiving
}
Enter fullscreen mode Exit fullscreen mode

When you DO need threading/async

  1. Multiple clients - need to handle connections concurrently
  2. Long processing - can't block the receive loop
  3. Real-time requirements - can't miss incoming data

C++ options:

// Option 1: std::thread with a queue
std::queue<Data> dataQueue;
std::mutex queueMutex;

std::thread receiver([&]{ /* push to queue */ });
std::thread processor([&]{ /* pop and process */ });

// Option 2: Boost.Asio (closest to Python's asyncio)
boost::asio::async_read(socket, buffer, [](auto ec, auto bytes) {
    process(buffer);
});
io_context.run();
Enter fullscreen mode Exit fullscreen mode

Bonus: Sockets vs Shared Memory

Aspect Sockets Shared Memory
Latency ~10-100μs ~100ns
Complexity Easy Harder (need mutex/semaphore)
Best for Different machines, < 10MB/s Same machine, > 100MB/s

My recommendation: Start with sockets — they're simpler and easier to debug. Only switch to shared memory if profiling shows it's a bottleneck.

For 300 bytes from a browser, sockets are more than enough!