I need to write a programm which uses threads and sockets. What is the best way to do it for different platforms (Linux, Windows, Mac).
I know about POSIX, but there is no POSIX on Win.
Are there any libraries handling that in a platform independent way?
Sockets are not part of C++ Standard so it depends on implementation. Generally they are not thread safe since send is not an atomic operation.
C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX.
Multithreaded Socket Programming describes that a Multithreaded Socket Server can communicate with more than one client at the same time in the same network.
A thread is a sequence of instructions that run independently of the program and of any other threads. Using threads, a multi-threaded server program can accept a connection from a client, start a thread for that communication, and continue listening for requests from other clients.
If you really want C (not C++), I suggest to use the standard POSIX threads on non-Windows platforms, and use pthreads-win32 on Windows. It supports both 32- and 64-bit, both MSVC and MinGW. It's current version (2.9.1) was released just one month ago, so the project is actively maintained. There's also a fork on github with some fixes in MSVC2010 project.
If C++ is also an option, I'd choose boost, because it's where the standard c++ evolves (the design of std::thread
in c++11 is an evolution from boost::thread
, etc.)
For the network part of your question, boost::asio
is the best choice if C++ is OK for you, otherwise didn't see anything comparable in C. In particular, boost::asio
supports I/O Completion Ports (IOCP)
on Windows, which is critical for performance. boost::asio
requires some time to learn, but in my personal opinion it worth every minute spent reading the documentation (which is great) and working with examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With