std::packaged_task传递任务

#include
#include
#include
#include 


template
class threadsafe_queue{
public:
    threadsafe_queue();
    threadsafe_queue(const threadsafe_queue &);
    threadsafe_queue &operator=(const threadsafe_queue &) = delete;
    void push(T &&new_value);
    bool try_pop(T & value);
    std::shared_ptr try_pop();

    void wait_and_pop(T & value);
    std::shared_ptr wait_and_pop();
    bool empty() const;

private:
    mutable std::mutex mut;
    std::queue data_queue;
    std::condition_variable data_cond;
};

template 
void threadsafe_queue::push(T &&new_value) {//接受右值,但是,new_value在函数内并非右边值,push的时候仍需std::move转化
    std::lock_guard lk(mut);//std::packaged_task不可拷贝,只能移动
    data_queue.push(std::move(new_value));
    data_cond.notify_one();
}

template 
void threadsafe_queue::wait_and_pop(T &value) {
    std::unique_lock lk(mut);
    data_cond.wait(lk,[this]{
        return !this->data_queue.empty();
    });
    value=data_queue.front();
    data_queue.pop();
}

template 
bool threadsafe_queue::try_pop(T &value) {
    std::lock_guard lk(mut);
    if(!data_queue.empty())
        return false;
    else
    {
        value=data_queue.front();
        data_queue.pop();
        return true;
    }
}

template 
std::shared_ptr threadsafe_queue::wait_and_pop() {
    std::unique_lock lk(mut);
    data_cond.wait(lk,[this]{
        return !this->data_queue.empty();
    });
    std::shared_ptr res(std::make_shared(std::move(data_queue.front())));
    data_queue.pop();
    return res;
}

template 
std::shared_ptr threadsafe_queue::try_pop() {
    std::lock_guard lk(mut);
    if(!data_queue.empty())
        return std::shared_ptr();
    std::shared_ptr res(std::make_shared(data_queue.front()));
    data_queue.pop();
    return res;
}

template 
bool threadsafe_queue::empty() const {
    std::lock_guard lk(mut);
    return data_queue.empty();
}

template 
threadsafe_queue::threadsafe_queue() {
}

template 
threadsafe_queue::threadsafe_queue(const threadsafe_queue &other) {
    std::lock_guard lk(other.mut);
    data_queue=other.data_queue;
}

void worker1(){
    std::cout<<"hello worker 1"<> & queue){

    queue.push(std::packaged_task(worker1));
    queue.push(std::packaged_task(worker2));
}

void getdata(threadsafe_queue> & queue){
    (*queue.wait_and_pop())();
    (*queue.wait_and_pop())();
}

int main()
{
    threadsafe_queue> queue;
    std::thread t1(product,std::ref(queue));
    std::thread t2(getdata,std::ref(queue));

    t1.join();
    t2.join();
    return 0;
}



你可能感兴趣的:(std::packaged_task传递任务)