Pavel.Zh
Pavel.Zh

Reputation: 477

How to create thread safe lib for C and C++ on Linux?

I want to write some library in C++11, which will be used in C and C++ programs (so all exported function will be marked as extern "C").

I want all exported functions to be thread-safe. So if I would write this library on windows, I can use Critical Section Objects, but what should I use in Linux?

Here's my options:

  1. POSIX mutexes
  2. C++11 std::mutex
  3. C++11 atomic variables
  4. Linux (POSIX) semaphores

Troubles: There is no guarantees of which thread - POSIX or C++11 - will be used in code which will use my library.

So 1) and 2) options cannot be used, because POSIX threads != C++11 threads.

Rest options look much slower than mutex-based solutions.

Does anybody know the correct way to create thread-safe library on Linux?

Upvotes: 2

Views: 1372

Answers (2)

rubenvb
rubenvb

Reputation: 76795

If your library is thread-safe, you should ensure no unsafe operations can happen when a user calls your library functions from different threads. Of course, it would be silly to not require the user to use at least some discretion him/herself, such as not calling modifying functions on the same object from multiple threads concurrently.

In the end, thread safety comes down to protecting your internal state with things like mutexes. Because it's internal state, what the user does outside of your library shouldn't matter, and thus it also doesn't matter what underlying library you use to provide this synchronisation. As you've written the library in C++11, I'd suggest using its provided threading primitives if they fit your needs.

Upvotes: 2

diametralpitch
diametralpitch

Reputation: 685

The question in your title seems different than what you are concerned with in the body. If you want to write thread safe code, there is no real answer except for following some guidelines of using discretion when accessing global variables and using a form of protection when accessing globals and or variables shared by threads.

You seem to be really asking about how to write portable multithreaded code. To say C++11 is not POSIX threads, from the perspective of a Linux based machine is not accurate. The purpose of std::thread is to provide an abstraction layer for the system's underlying thread library. In the case of using std::thread on Linux, you will eventually be making pthread calls. As a test, try to compile a program using C++ threads without linking to libpthread (-lpthread) and you should see it fail.

Upvotes: 4

Related Questions