Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use threading and sockets in C in a platform independent way

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?

like image 833
drivel Avatar asked Jun 24 '12 11:06

drivel


People also ask

Are C sockets thread-safe?

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.

Does C allow multithreading?

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.

Why we use multithreading in socket programming?

Multithreaded Socket Programming describes that a Multithreaded Socket Server can communicate with more than one client at the same time in the same network.

What is threading in socket programming?

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.


1 Answers

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.

like image 133
vond Avatar answered Oct 06 '22 00:10

vond