线程安全队列和多任务同步

上回说到如果有一个请求,分成了很多互不干扰的task,放入了队列里,那么该请求的这些task怎么做同步呢?需要一个同步机制,直接上代码;

class Notification {
 public:
     Notification() = default;
     ~Notification() {

     }

     int32_t init() {
         if (init_) return 0;
         event_fd_ = eventfd(0,0);
         if (event_fd_ < 0) return -1;
         epoll_fd = epoll_create(1);
         if (epoll_fd < 0) return -2;
         struct epoll_event event;
         event.data.fd = event_fd_;
         event.events = EPOLLIN;
         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, event_fd_, &event) != 0)
             return -3;
         init_ = true;
         return 0;
     }
     void set(int32_t num) {
         num_ = num;
     }
     int32_t waitDone() {
         while(num_.load(std::memory_order_relaxed) != 0)
             wait();
         return 0;
     }
     int32_t Wait() const {
        struct epoll_event event;
        epoll_wait(epoll_fd_, &event, 1, -1);
        uint64_t v;
        auto ret = ::read(event_fd_, &v, sizeof(uint64_t));
        (void)ret;
        return 0;
    }
    void notify() {
        num_.fetch_sub(1, std::memory_order_relaxed);
        uint64_t v = 1;
        auto ret = ::write(event_fd_, &v, sizeof(uint64_t));
        (void)ret;
    }
 private:
     bool init_ {false};
     std::atomic<int32_t> num_;
     int32_t event_fd_ {-1};
     int32_t epoll_fd {-1};

}

使用的时候:

static thread_local Notification* notification = new Notification();

if (notification->init() != 0)

        return -1;

notification->set(task_num);  // task_num是分成的任务数量

然后在每一个任务里调用

notification->notify();

最后等待所有任务执行完成

notification->wait_done();

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值