views:

180

answers:

3

I was reading this: http://en.wikipedia.org/wiki/Thread_safety

Is the following function thread-safe?

void foo(int y){
    int * x = new int[50];
    /*...do some stuff with the allocated memory...*/
    delete [] x;
}

In the article it says that to be thread-safe you can only use variables from the stack. Really? Why? Wouldn't subsequent calls of the above function allocate memory elsewhere?

Edit: Ah. Looks like I misread this part of the article:

A subroutine is reentrant, and thus thread-safe, if

  • the only variables it uses are from the stack

(I took it to mean

A subroutine is reentrant, and thus thread-safe, if and only if

  • the only variables it uses are from the stack

, which according to the answers below, is not the case)

A: 

new and delete may or may not be thread safe. They probably are, but that is implementation-dependent. See: http://stackoverflow.com/questions/796099/c-new-operator-thread-safety-in-linux-and-gcc-4

To be thread safe, a function must either use stack variables or synchronize its access to other resources with other threads. As long as separate calls to new allocate different space on the heap when called from different threads, you should be fine.

WhirlWind
+2  A: 

It doesn't say you can only use stack variables, it says that using heap variables "suggests the need for careful examination to see if it is unsafe".

new and delete are normally implemented in a threadsafe way (not sure that the standard guarantees that though) so your code above will probably be fine.

Plus usual recommendations of using std::vector instead of manually allocating an array, but I assume you only provided that as an example :)

Peter
I recall operating in an environment where they weren't. Now *that* was hairy.
Joshua
It's fortunate that you can override them then :)
Matthieu M.
+3  A: 

If you are coding in an environment that supports multi-threading, then you can be pretty sure new is thread safe.

Although the memory is on the heap, the pointer to it is on the stack. Only your thread has the pointer to this memory, and so there is no risk of concurrent modification - no other thread knows where the memory is to modify it.

You would only get a problem with thread safety if you were to pass this pointer to another thread that would then concurrently modify this memory at the same time as your original (or another) thread.

mdma
Thanks. Tough choice between your answer and Peter's, but your helpful hint at the end was relevant, while his was about vectors :)
Cam