Thread safety with heap-allocated memory

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

提交回复
热议问题