Why doesn't C++ call unknown code with the lock?
This article mainly explains why C++ should not call unknown code with a lock. Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn why C++ should not call unknown code with a lock.
CP.22: never call unknown code (such as callback) with a lock
Reason (reason)
If you don't know what a piece of code does, you are risking deadlock.
If you don't know what a piece of code will do, you are at risk of deadlock.
Example (instance)
Void do_this (Foo* p)
{
Lock_guard lck {my_mutex}
/ /... Do something...
P-> act (my_data)
/ /...
}
If you don't know what Foo::act will do (maybe this is a virtual function that calls a member of a derived class), it may also (recursively) call do_this and cause a deadlock in my_mutex. It may also lock another mutex and fail to return within a reasonable time, resulting in a delay in all code that calls do_this.
Example (sample)
A common example of a problem caused by calling unknown code is when the called function attempts to reaccess an object in a locked state. Such problems can usually be solved by using a reentrant recursive_mutex. For example:
Recursive_mutex my_mutex
Template
Void do_something (Action f)
{
Unique_lock lck {my_mutex}
/ /... Do something...
F (this); / / f will do something to * this
/ /...
}
If, as it is likely, f () invokes operations on * this, we must make sure that the object's invariant holds before the call.
If, because f () may invoke the operation against * this, we must ensure that the object invariants before the call can be maintained.
Enforcement (implementation recommendations)
Flag calling a virtual function with a non-recursive mutex held
Tag calls a virtual function that holds a non-reentrant mutex.
Flag calling a callback with a non-recursive mutex held
Tag calls a callback function that holds a non-reentrant mutex.
At this point, I believe you have a deeper understanding of "why C++ doesn't hold the lock and call unknown code". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!