【问题标题】:Thread pools not working with large number of tasks线程池不能处理大量任务
【发布时间】:2022-01-18 04:21:32
【问题描述】:

我正在尝试使用本机 C++ 创建一个线程池,并且我正在使用“C++ Concurrency in Action”一书中的代码清单。我遇到的问题是,当我提交的工作项多于线程数时,并非所有工作项都完成了。在下面的简单示例中,我尝试提交 runMe() 函数 200 次,但该函数只运行了 8 次。 这似乎不应该发生,因为在代码中,work_queue 与工作线程是分开的。代码如下:

#include "iostream"
#include "ThreadPool.h"
void runMe()
{
    cout << "testing" << endl;
}

int main(void)
{
    thread_pool pool;
    for (int i = 0; i < 200; i++)
    {
        std::function<void()> myFunction = [&] {runMe(); };
        pool.submit(myFunction);
    }


    return 0;
}

ThreadPool.h 类

#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();
    }
    int size()
    {
        return data_queue.size();
    }
};

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();
                numActiveThreads--;
            }
            else
            {
                std::this_thread::yield();
            }
        }
    }
public:
    int numActiveThreads;
    thread_pool() : done(false), joiner(threads), numActiveThreads(0)
    {
        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));
        numActiveThreads++;
    }
    int size()
    {
        return work_queue.size();
    }
    bool isQueueEmpty()
    {
        return work_queue.empty();
    }
};

知道如何正确使用work_queue吗?

【问题讨论】:

  • 甚至不是main(),所以这不是minimal reproducible example。另外,“崩溃”是您的解释,您观察到了什么?作为新用户,请拨打tour阅读How to Ask
  • threadsafe_queue::size() 需要互斥锁以确保它看到任何更新(就像您为 threadsafe_queue::empty() 所做的那样)
  • 可能task不支持被正确移动/复制我们需要查看类定义。
  • threadsafe_queue::wait_and_pop 中,如果底层队列在进入时为空,则此方法将持有锁,因为该方法持有锁,所以队列永远不会添加任务。即如果我们在threadsafe_queue::wait_and_pop 中等待(因为队列是空的)threadsafe_queue::push 在另一个线程上会阻塞。
  • @UlrichEckhardt 感谢您的反馈。我用一个简单的 main 函数修改了这个例子。此代码运行但未运行测试功能 200 次。

标签: c++ multithreading native


【解决方案1】:

poolmain 结束时被销毁,你的析构函数设置done,使你的工作线程退出。

你应该让析构函数(或者main,如果你想让它成为可选的)在设置标志之前等待队列耗尽。

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2012-02-12
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2015-09-03
    • 1970-01-01
    相关资源
    最近更新 更多