Home > Software engineering >  Thread pool not completing all tasks
Thread pool not completing all tasks

Time:12-17

I have asked a simpler version of this question before and got the correct answer: Thread pools not working with large number of tasks Now I am trying to run tasks from an object of a class in parallel using a thread pool. My task is simple and only prints a number for that instance of class. I am expecting numbers 0->9 get printed but instead I get some numbers get printed more than once and some numbers not printed at all. Can anyone see what I am doing wrong with creating tasks in my loop?

#include "iostream"
#include "ThreadPool.h"
#include <chrono>
#include <thread>

using namespace std;
using namespace dynamicThreadPool;

class test {
    int x;
public:
    test(int x_in) : x(x_in) {}
    void task()
    {
        cout << x << endl;
    }
};

int main(void)
{
    thread_pool pool;
    for (int i = 0; i < 10; i  )
    {
        test* myTest = new test(i);
        std::function<void()> myFunction = [&] {myTest->task(); };
        pool.submit(myFunction);
    }
    while (!pool.isQueueEmpty())
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        cout << "waiting for tasks to complete" << endl;
    }

    return 0;
}

And here is my thread pool, I got this definition from "C Concurrency in Action" book:

#pragma once
#include <queue>
#include <future>
#include <list>
#include <functional>
#include <memory>

template<typename T>
class threadsafe_queue
{
private:
    mutable std::mutex mut;
    std::queue<T> data_queue;
    std::condition_variable data_cond;
public:
    threadsafe_queue() {}
    void push(T new_value)
    {
        std::lock_guard<std::mutex> lk(mut);
        data_queue.push(std::move(new_value));
        data_cond.notify_one();
    }
    void wait_and_pop(T& value)
    {
        std::unique_lock<std::mutex> lk(mut);
        data_cond.wait(lk, [this] {return !data_queue.empty(); });
        value = std::move(data_queue.front());
        data_queue.pop();
    }
    bool try_pop(T& value)
    {
        std::lock_guard<std::mutex> lk(mut);
        if (data_queue.empty())
            return false;
        value = std::move(data_queue.front());
        data_queue.pop();
        return true;
    }
    bool empty() const
    {
        std::lock_guard<std::mutex> lk(mut);
        return data_queue.empty();
    }
};

class join_threads
{
    std::vector<std::thread>& threads;
public:
    explicit join_threads(std::vector<std::thread>& threads_) : threads(threads_) {}
    ~join_threads()
    {
        for (unsigned long i = 0; i < threads.size(); i  )
        {
            if (threads[i].joinable())
            {
                threads[i].join();
            }
        }
    }
};

class thread_pool
{
    std::atomic_bool done;
    threadsafe_queue<std::function<void()> > work_queue;
    std::vector<std::thread> threads;
    join_threads joiner;
    void worker_thread()
    {
        while (!done)
        {
            std::function<void()> task;
            if (work_queue.try_pop(task))
            {
                task();
            }
            else
            {
                std::this_thread::yield();
            }
        }
    }
public:
    thread_pool() : done(false), joiner(threads)
    {
        unsigned const thread_count = std::thread::hardware_concurrency();
        try
        {
            for (unsigned i = 0; i < thread_count; i  )
            {
                threads.push_back(std::thread(&thread_pool::worker_thread, this));
            }
        }
        catch (...)
        {
            done = true;
            throw;
        }
    }
    ~thread_pool()
    {
        done = true;
    }
    template<typename FunctionType>
    void submit(FunctionType f)
    {
        work_queue.push(std::function<void()>(f));
    }
    bool isQueueEmpty()
    {
        return work_queue.empty();
    }
};

CodePudding user response:

There's too much code to analyse all of it but you take a pointer by reference here:

{
    test* myTest = new test(i);
    std::function<void()> myFunction = [&] {myTest->task(); };
    pool.submit(myFunction);
} // pointer goes out of scope

After that pointer has gone out of scope you will have undefined behavior if you later do myTest->task();.

To solve that immediate problem, copy the pointer and delete the object afterwards to not leak memory:

{
    test* myTest = new test(i);
    std::function<void()> myFunction = [=] {myTest->task(); delete myTest; };
    pool.submit(myFunction);
}

I suspect this could be solved without using new at all, but I'll leave that up to you.

  • Related