Junior — Middle
How can data be sent to a server without blocking the main execution thread?
sobes.tech AI
Answer from AI
To send data to the server without blocking the main thread in C/C++, multithreading can be used. For example, creating a separate thread that handles sending data while the main thread continues working.
Example using std::thread:
#include <iostream>
#include <thread>
#include <chrono>
void sendDataToServer() {
// Simulate data sending
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Data sent to server" << std::endl;
}
int main() {
std::thread sender(sendDataToServer);
std::cout << "Main thread continues work" << std::endl;
sender.join(); // Wait for sending to finish if needed
return 0;
}
You can also use asynchronous calls (std::async) or libraries for async I/O, such as Boost.Asio.