Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are memmove and malloc thread safe?

Tags:

c

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).

like image 310
Rad'Val Avatar asked Apr 06 '11 17:04

Rad'Val


People also ask

Is malloc multithread safe?

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).

Is free () thread-safe?

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.

Is malloc thread-safe on Windows?

Provided you're linking with thread-safe libraries and using the correct flags, yes, malloc should be thread-safe.

Is time function thread-safe?

The POSIX spec says time is required to be thread safe, and so it is.


3 Answers

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.

like image 138
Jerry Coffin Avatar answered Oct 29 '22 20:10

Jerry Coffin


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.

like image 34
Black Frog Avatar answered Oct 29 '22 22:10

Black Frog


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.

like image 37
Ira Baxter Avatar answered Oct 29 '22 20:10

Ira Baxter