Is C ++ `free` a thread safe function?

That is, if my C ++ application allocates memory in one thread using malloc , will free deactivate memory successfully if it is called from another thread, or can I expect it to throw an exception? Both threads belong to the same process. I am using Visual Studio 2008. Thank you.

+4
source share
5 answers

The current standard makes no guarantees regarding streams. In most implementations, malloc and free can be called from different threads. Visual C ++ heap code also serializes access to heaps, so you should be fine.

+4
source

If malloc and free correctly synchronized, freeing memory in another thread will be fine and safe. Moreover, this statement is true in accordance with the C ++ 0x standard. As mentioned in @Ashot, the current C ++ 03 standard deals only with a single-threaded execution model

+2
source

It is thread safe in this sense (the malloc pool is a global process, not a local thread), but not in the sense that it behaves securely when called when another thread calls malloc() or free() .

+1
source

The current C ++ standard does not even know about threads. So by standard, I don’t think you can say whether it is good or not. However, all threads in the program have the same address space, so there should be Ok for a free object in another thread.

+1
source

If the C compiler and the OS support threads, then it will be safe.

If your compiler is on Windows, you want to make sure that you are linking to multi-threaded runtime libraries. Or, if your compiler supports the -pthread option or something similar, then it is also safe.

If the compiler has a flag, such as -pthread, do not assume that all are thread-safe unless you use this flag. Using the flag will link in different libraries and set different preprocessor macros. It is possible that a whole other thread-safe runtime is bound during the execution of this flag.

0
source

Source: https://habr.com/ru/post/1343994/


All Articles