I have some code that moves bytes in a buffer using memmove()
. The buffer is accessed by multiple threads. I get a very weird behavior; sometimes the buffer it's not what it should be and I was thinking if memmove()
or/and malloc()
are thread safe. I'm working on iOS (in case this is platform dependent).
None of the common versions of malloc allow you to re-enter it (e.g. from a signal handler). Note that a reentrant routine may not use locks, and almost all malloc versions in existence do use locks (which makes them thread-safe), or global/static variables (which makes them thread-unsafe and non-reentrant).
By default, new/delete are often not thread safe in a FreeRTOS app because the basic malloc and free are not thread safe. Some embedded libraries have hooks that can be defined to make these functions thread safe.
Provided you're linking with thread-safe libraries and using the correct flags, yes, malloc should be thread-safe.
The POSIX spec says time is required to be thread safe, and so it is.
In an implementation that provides threads, malloc
will normally be thread safe (i.e., it will take steps to assure the heap doesn't get corrupted, even if malloc
gets called from multiple threads). The exact way it will do that varies: some use a single heap, and internal synchronization to ensure against corruption. Others will use multiple heaps, so different threads can allocate memory simultaneously without collisions.
memmove
will normally be just like if you did assignments in your own code -- if you're sharing a buffer across threads, it's your responsibility to synchronize access to that data.
You should be using a mutex (NSLock) as a protective barrier around accessing your buffer. Take a look at Synchronization in Apple's Threading Programming Guide.
Malloc may be thread-safe. The standard doesn't require it, but many C compilers are used in systems whose applications requires thread safety, and your particular compiler's library may be thread safe, or offer a thread safe option. I don't know about iOS.
Memmove (or any other kind of block move) is not thread safe, any more than an assignment statement is thread safe.
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