Alex Rivera | Logout

Thread Safety in C

Asked 2010-01-08T18:03:11.753
16

imagine I write a library in C. Further, imagine this library to be used from a multi-threaded environment. How do I make it thread-safe? More specific: How do I assure, that certain functions are executed only by one thread at a time?

In opposite to Java or C# for example, C has no means to deal with threads/locks/etc., nor does the C standard library. I know, that operating systems support threads, but using their api would restrict the compatibility of my library very much. Which possibilities do I have, to keep my library as compatible/portable as possible? (for example relying on OpenMP, or on Posix threads to keep it compatible with at least all unix-like operating systems?)

Edit
Report

1 Answer

1

If your goal is to be compatible on unix-like operating systems, I would use POSIX threading.

That being said, if you want to support windows as well, you'll need to have two code paths for this - pthreads on unix and Windows threads on Windows. It's fairly easy to just make your own "thread library" to wrap these.

There are quite a few that do this (like OpenThreads), but most of them I've used are C++, not C.

answered 2010-01-08T18:06:50.357

Your Answer