RippeR37/libbase

Add ability to do final cleanup before stopping/joining a thread

Closed this issue · 0 comments

Add functionality that will allow to queue a callback on given thread/task runner right before stopping it. The rationale is somewhat related to #16 and might be needed to ensure that thread-affine resources are correctly released as the last thing executed on that thread. This is to handle cases where one might assume that object lives as long as the thread (or even outlives it) so it would post-task to that thread with e.g. Unretained() wrapper and you don't want to change this, but you still have to destroy that object on that particular thread (i.e. cannot destroy it on any other threads).

Currently, you could try to do:

  01:    thread.TaskRunner()->PostTask(FROM_HERE, /* release_the_resource_callback */);
  02:    thread.Join(); // or .Stop()

but there is no guarantee that there won't be any other task posted before 2nd line and after 1st. The new functionality could work like:

  thread.StopWithCleanup(FROM_HERE, /*release_the_resource_callback*/);

which would atomically queue the callback as the last callback that will be executed and stop the thread (which would block queuing any more tasks and wait until all existing ones (including the release_the_resource_callback) are completed.