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
It's thread-safe in that sense (the malloc
pool is process-global, not thread-local), but not in the sense of behaving sanely if called while another thread is calling malloc()
or 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.
精彩评论