vendredi 23 février 2018

How to join all threads before deleting the ThreadPool

I am using a MultiThreading class which creates the required number of threads in its own threadpool and deletes itself after use.

std::thread *m_pool;      //number of threads according to available cores
std::mutex m_locker;
std::condition_variable m_condition;
std::atomic<bool> m_exit;
int m_processors    

m_pool = new std::thread[m_processors]

void func()
{
   //code
}

for (int i = 0; i < m_processors; i++)
{
    m_pool[i] = std::thread(func);
}

void reset(void)
{
    {
        std::lock_guard<std::mutex> lock(m_locker);
        m_exit = true;
    }
    m_condition.notify_all();

    for(int i = 0; i <= m_processors; i++)
        m_pool[i].join();
    delete[] m_pool;
}

After running through all tasks, the for-loop is supposed to join all running threads before delete[] is being executed.
But there seems to be one last thread still running, while the m_pool does not exist anymore.
This leads to the problem, that I can't close my program anymore.
Is there any way to check if all threads are joined or wait for all threads to be joined before deleting the threadpool?

Aucun commentaire:

Enregistrer un commentaire