wuyuanyi135/Simex

Improvement in construction and destruction management

Closed this issue · 1 comments

Currently this library assumes every block resource should be initiated and started in onStart callback and being destroyed by onTerminate. There are a few problems with this scheme:

  1. Exception in onStart will prevent onTerminate from being called. This has been somehow resolved by using SS_OPTION_CALL_TERMINATE_ON_EXIT
  2. Exception in onTerminate will cause partially destructed object, possibly crash MATLAB.

The question is: should we change the finalization with e.g. class destructor with unique_ptr?
The current destructor of block shall be called in the simulink mdlTerminate callback, when the block persistent registry removes this block. That means, we have to rely on the invocation of mdlTerminate anyway, so the workaround for problem 1 will be retained to ensure the proper finalization of the blocks.

Next, should we use try/catch blocks in onTerminate to release resources, or use the destructor and customized deleters?

Using the deleter: the data and *deleters of unique_ptr or shared_ptr will be assigned in onStart. The destructor will call the deleters when the block should be stopped. If the routine was for block meta information, the destructor will deal with null pointers - nothing special will happen.

Pros:

  • no explicit delete in onTerminate or destructor;
  • The creation of the object is adjacent to its destroy callback - easy to maintain;
  • Works even if the derived class forgets to call the parent's onTerminate

Cons: the delete order becomes important: e.g., backgroundThread may be deleted prior to the ioService, where calling backgroundThread.join will lead to deadlock. A possible fix is that, stop ioService inside the deleter of the thread. Note that the validity of the object should be checked because it may have been released.

Is it worth switching?
working on branch new_destructor

It hangs for some reason. Probably due to stopping ioservice is asynchronous. The destructor won't wait for the background thread to stop the ioservice and will release the resource dangerously. This plan will not be temporarily closed..