c++ - 为什么不在 pop 之后运行任务并返回 true?

标签 c++ concurrency c++11

我运行以下来自书籍 c++ concurrency in action 的示例,并通过其提交传递函数 a、b 和 c,它打印 pop 并确定返回 true,但为什么不打印“开始任务” 似乎没有运行 task()

#include <thread>
#include <atomic>
#include <vector>
#include <queue>

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

template<typename T>
class thread_safe_queue
{
private:
    mutable std::mutex mut;
    std::queue<T> data_queue;
    std::condition_variable data_cond;
public:
    thread_safe_queue(){}
    thread_safe_queue(thread_safe_queue const& other)
    {
        std::lock_guard<std::mutex> lk(other.mut);
        data_queue=other.data_queue;
    }
    void push(T new_value)
    {
        std::lock_guard<std::mutex> lk(mut);
        data_queue.push(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();});
        data_cond.wait(lk);
        value=data_queue.front();
        data_queue.pop();
    }
    std::shared_ptr<T> wait_and_pop()
    {
        std::unique_lock<std::mutex> lk(mut);
        //data_cond.wait(lk,[this]{return !data_queue.empty();});
        data_cond.wait(lk);
        std::shared_ptr<T> res(new T(data_queue.front()));
        data_queue.pop();
        return res;
    }
    bool try_pop(T& value)
    {
        std::lock_guard<std::mutex> lk(mut);
        if(data_queue.empty())
        return false;
        value=data_queue.front();
        data_queue.pop();
        printf("pop");
        return true;
    }
    std::shared_ptr<T> try_pop()
    {
        std::lock_guard<std::mutex> lk(mut);
        if(data_queue.empty())
        return std::shared_ptr<T>();
        std::shared_ptr<T> res(new T(data_queue.front()));
        data_queue.pop();
        return res;
    }
    bool empty() const
    {
        std::lock_guard<std::mutex> lk(mut);
        return data_queue.empty();
    }
};

class thread_pool
{
    std::atomic_bool done;
    thread_safe_queue<std::function<void()> > work_queue;
    std::vector<std::thread> threads;
    join_threads joiner;
    void worker_thread()
    {
        while(!done)
        {
            //printf("workerthread");
            std::function<void()> task;
            if(work_queue.try_pop(task))
            {
                printf("task start\n");
                task();
                printf("task end\n");
            }
            else
            {
                std::this_thread::yield();
            }
        }
    }
public:
    thread_pool() : joiner(threads),done(false)
    {
        unsigned const thread_count=std::thread::hardware_concurrency();
        try
        {
            for(unsigned i=0;i<6;++i)
            {
                printf("push %d",i);
                threads.push_back(std::thread(&thread_pool::worker_thread,this));
            }
        }
        catch(std::bad_alloc)
        {
            done=true;
            throw;
        }
    }
    ~thread_pool()
    {
        done=true;
    }
    template<typename FunctionType>
    void submit(FunctionType f)
    {
        work_queue.push(std::function<void()>(f));
    }
};
void a()
{
    //while(true)
    {
        printf("a\n");
    }
}
void b()
{
    //while(true)
    {
        printf("b\n");
    }
}
void c()
{
    //while(true)
    {
        printf("c\n");
    }
}
int main()
{
    printf("begin\n");
    thread_pool* pool = new thread_pool(); //start thread pool
    printf("submit start\n");
    pool->submit((*a)); // pass function to queue
    pool->submit((*b));
    pool->submit((*c));

    printf("submit finish\n");
    while(pool->done == false)
        std::this_thread::sleep(std::milliseconds(1));
}

最佳答案

修复所有编译错误后,在 Linux 上使用 GCC 4.6.1 编译并运行,产生以下输出:

begin
push 0push 1push 2push 3push 4push 5submit start
submit finish
poptask start
a
task end
poptask start
b
task end
poptask start
c
task end

在那之后,它会一直处于无限循环中,因为 done 永远不会变成 true

看起来实际上打印了“任务开始”。

关于c++ - 为什么不在 pop 之后运行任务并返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7858866/

相关文章:

c++ - 是否有用于 Visual C++ 的编译器标志来检查调用 printf() 的类型安全性?

c++ - Raspberry PI GCC 4.8.2 build boost 1.56 原子错误

c++ - 比较文件统计时间

c++ - x++ 和++x 在c 中不能作为左值(左值)?

java - 在 Java 中使用 POI 时如何增加 Excel 计算引擎的限制?

python - 在多处理循环中捕获异常

java - 保证回调总是异步执行的最佳方式?

c++ - 为什么必须在父类(super class)中实现虚函数?

c++ - 向类添加仅移动类型会使该类成为仅移动类型?

c++ - cout怎么知道如何格式化不同的类型呢?