Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety with heap-allocated memory

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)

like image 906
Cam Avatar asked May 16 '10 23:05

Cam


People also ask

Is heap memory thread-safe?

This global heap is fully thread-safe, meaning that multiple threads can allocate and free memory from it simultaneously without corrupting the heap. To help provide thread safety, the heap has to serialize access to itself.

Why is heap memory not thread-safe?

Heap-memory is also not threaded-safe as Stack-memory because data stored in Heap-memory are visible to all threads. Size of Heap-memory is quite larger as compared to the Stack-memory. Heap-memory is accessible or exists as long as the whole application(or java program) runs.

Is heap thread-safe in Java?

If the heap is full, java. lang. OutOfMemoryError is thrown by JVM. It is not thread-safe like a stack.

Do threads have their own heap allocated area?

Depends on the OS. The standard c runtime on windows and unices uses a shared heap across threads. This means locking every malloc/free. On Symbian, for example, each thread comes with its own heap, although threads can share pointers to data allocated in any heap.


1 Answers

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.

like image 87
mdma Avatar answered Oct 22 '22 11:10

mdma