Are memmove and malloc thread safe?
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 th开发者_运维百科read safe. I'm working on iOS (in case this is platform dependent).
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.
Since the current C standard does not specify threads, it has nothing to say about thread safety. Whenever you have threads, you're dealing with a system that has placed further requirements, beyond the basic C language standard's requirements, on how the standard library functions behave. I'm not sure what requirements iOS makes, but POSIX and Windows both require malloc
to be thread-safe, and I'd find it hard to believe any system designed after the mid 90s would not make this requirement.
Note that the upcoming C1x standard will specify threads, and if the implementation has threads, then malloc
will be required to be thread-safe.
No, since the standard C library doesn't have a concept of threads, the functions it defines can't be.
精彩评论