Re:The Best C++ Interview Question – Ever
by pavlov on Monday December 07, 2009 @06:18PM
(#982495)
Why is alloca() non-thread-safe? Each thread has its own stack.
[ Parent
| on HN ]
The way I thought about it, concurrent access to objects allocated via alloca() would probably not be explicitly protected by a lock. Threads can also be killed and spawned while other threads are accessing its stack contents. Anyway, I can think of more use cases where it's a bad idea to allocate objects on thread's stacks that you're planning to share.
Yeah, sharing objects on the thread-local stack is definitely a bad idea.
But as long as the alloca'd memory is only accessed from within the same thread, it is -- AFAIK -- safe to call alloca() simultaneously from multiple threads, the same as malloc(). I think that qualifies as thread-safety by the usual definition: i.e. the function doesn't access statics or globals.
(Of course this will vary depending on the CRT. I don't think any UNIXes nowadays ship without threading support in the CRT, but Microsoft Visual C++ used to have separate thread-safe and non-thread-safe C libraries.)