簡體   English   中英

線程池未完成所有任務

[英]Thread pool not completing all tasks

我之前問過這個問題的簡單版本並得到了正確答案: 線程池無法處理大量任務現在我正在嘗試使用線程池從 class 的 object 並行運行任務。 我的任務很簡單,只為 class 的實例打印一個數字。 我期待數字 0->9 被打印出來,但是我得到一些數字被打印了不止一次,而一些數字根本沒有打印出來。 誰能看到我在循環中創建任務時做錯了什么?

#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;
}

這是我的線程池,我從“C++ Concurrency in Action”一書中得到了這個定義:

#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();
    }
};

有太多代碼無法分析所有內容,但您可以在此處通過引用獲取指針:

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

在該指針離開 scope 之后,如果您稍后執行myTest->task();您將有未定義的行為 .

為了解決這個直接的問題,復制指針並delete object 以不泄漏 memory:

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

我懷疑這可以在不使用new的情況下解決,但我會留給你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM