简体   繁体   中英

Is the C++ `free` function thread-safe?

That is, if my C++ application allocates memory in one thread using malloc , will free successfully de-allocate the memory, if 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. Thanks.

The current standard doesn't make any guarantees about threads. On most implementations, malloc and free may be called from different threads. Visual C++ heap code also serializes access to heaps, so you should be fine.

If malloc and free are properly synchronized, deallocating memory in another thread is perfectly fine and safe. Moreover, this claim is correct according to C++0x standard. As @Ashot mentioned, the current C++03 standard deals only with singlethreaded execution model

从某种意义上讲,它是线程安全的( malloc池是进程全局的,而不是线程本地的),但是如果在另一个线程调用malloc()free()被调用则不会表现得很安全。

The current C++ standard doesn't even know about threads. So in terms of standard I don't think you can tell whether it is ok or not. However all threads in a program share the same address space, so it must be Ok to free object in other thread.

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

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

If the compiler does have a flag like -pthread then don't assume things are thread-safe unless you use that flag. Using the flag will link in different libraries and set different preprocessor macros. It's entirely possible that a whole different thread-safe C runtime is linked in when that flag is given.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM