Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Unix don't have a thread-safe malloc?

I want my C program to be portable even on very old Unix OS but the problem is that I'm using pthreads and dynamic allocation (malloc). All Unix I know of have a thread-safe malloc (Linux, *BSD, Irix, Solaris) however this is not guaranteed by the C standard, and I'm sure there are very old versions where this is not true.

So, is there some list of platforms that I'd need to wrap malloc() calls with a mutex lock? I plan to write a ./configure test that checks if current platform is in that list.

The other alternative would be to test malloc() for thread-safety, but I know of no deterministic way to do this. Any ideas on this one too?

like image 792
jimis Avatar asked May 12 '13 17:05

jimis


1 Answers

The only C standard that has threads (and can thus is relevant to your question) is C11, which states:

For purposes of determining the existence of a data race, memory allocation functions behave as though they accessed only memory locations accessible through their arguments and not other static duration storage.

Or in other words, as long as two threads don't pass the same address to realloc or free all calls to the memory functions are thread safe.

For POSIX, that is all Unix'es that you can find nowadays you have:

Each function defined in the System Interfaces volume of IEEE Std 1003.1-2001 is thread-safe unless explicitly stated otherwise.

I don't know from where you take your assertion that malloc wouldn't be thread safe for older Unixes, a system with threads that doesn't implement that thread safe is pretty much useless. What might be a problem on such an older system is performance, but it should always be functional.

like image 68
Jens Gustedt Avatar answered Nov 15 '22 09:11

Jens Gustedt