Thread safety with heap-allocated memory

前端 未结 3 1980
自闭症患者
自闭症患者 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: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.

提交回复
热议问题