Thread safety with heap-allocated memory

前端 未结 3 1933
自闭症患者
自闭症患者 2021-02-05 17:46

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];
    /*...         


        
相关标签:
3条回答
  • 2021-02-05 18:27

    new and delete may or may not be thread safe. They probably are, but that is implementation-dependent. See: 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.

    0 讨论(0)
  • 2021-02-05 18:28

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

    0 讨论(0)
  • 2021-02-05 18:37

    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.

    0 讨论(0)
提交回复
热议问题