mardi 31 octobre 2017

How to remove this once member thread is finished

The goal is to implement the Worker which executes tasks in a separate thread. The problem is to design the Worker shutdown path correctly. So:

class Worker
{
    /* ... */
    /**
     * @brief Thread pool worker constructor
     *
     * Runs the worker's taskRunner() in the stand alone thread.
    */
    Worker( ThreadPool * threadPool )
    {
        /* Run the task runner in new thread */
        this->mThread = std::thread( std::bind( & Worker::taskRunner, this, threadPool ) );
    }
    /* ... */
};

The worker runs it's member method Worker::taskRunner in a standalone thread. The taskRunner looks like this (unnecessary stuff removed):

void taskRunner( ThreadPool * threadPool )
{
    /* Infinite loop */
    while( this->getState() != State::TERMINATED )
    {
        /* ... */
    }

    /* At this point, the thread is going to be finished */
}

Once the infinite loop of the taskRunner is exited I would like to delete the Worker itself which instance is held in ThreadPool class in std::list collection:

std::list<std::shared_ptr<Worker>> mWorkers;

I would like to use the void std::list::remove( const T& value ); method.

The problem is in which scope this remove() is called.

  1. If I call it at the end of the taskRunner() method, it is going to be executed in scope of the Worker's thread, right? But is it correct approach to delete the parent object from it's member thread?
  2. I also thought about using boost::signals2::signal to notify the worker object itself it's thread is finished and so the Worker can ask the thread pool to remove itself...? Isn't is an overkill? Would it be a meaningfull solution to signal between main and worker's thread?

In general I would like to avoid any blocking pattern in main thread (where the Worker is running)... Many thanks in advance to anyone for any idea how to solve this problem...

Aucun commentaire:

Enregistrer un commentaire