[英]Is delete thread-safe?
int *p = new int;
// delete p in thread 1
// delete p in thread 2
I know that make p
equals to nullptr
is a good behavior but for now I just want to know if delete
is thread-safe? 我知道make p
等于nullptr
是一个好行为,但是现在我只想知道delete
是否是线程安全的? Do I need to use lock for the case above? 在上述情况下,我需要使用锁吗?
Yes, I delete the same object twice. 是的,我两次删除同一对象。
This is because that I found that delete p
twice in the same thread would make a core dumped error, whereas delete p
twice in two threads can not make any error. 这是因为我发现在同一线程中两次delete p
会导致核心转储错误,而在两个线程中两次delete p
不会造成任何错误。
I know that double delete is an UB so I want to know if delete
is thread-safe, meaning that if we enter the function delete
twice at the same time, we are safe because of it is thread-safe. 我知道double delete是UB,所以我想知道delete
是否是线程安全的,这意味着如果我们同时输入两次delete
函数,那么它是线程安全的,因此很安全。
You can use the following approach to achieve what you want by using a synchronization mechanism: Make sure that the deletion of p
and setting it to nullptr
can only be done by a single thread at a given moment: 您可以使用以下方法通过使用同步机制来实现所需的目标:确保删除p
并将其设置为nullptr
只能在给定的时刻由单个线程完成:
// multiple threads
// ...
// single thread (critical region)
delete p;
p = nullptr;
// multiple threads
// ...
This way, a second delete by another thread does nothing, since nullptr
will be what is going to be passed to delete
. 这样,另一个线程执行的第二次删除操作将nullptr
,因为nullptr
将是要传递给delete
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.