lgy514

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <deque>
#include <vector>
#include <condition_variable>
class pc {
public:
    pc() {
        _size = 1;
        v = std::make_unique<std::vector<unsigned char>[]>(_size);

      for (int sq = 0; sq < _size; sq++)
      {
        v[sq].resize(1024);
      }

    };

    pc(int size) :_size(size) {
        v = std::make_unique<std::vector<unsigned char>[]>(size);
      for (int sq = 0; sq < _size; sq++)
      {
        v[sq].resize(1024);
      } }; pc(
const pc &) = delete; pc & operator= (const pc &) = delete; void p(char* t,int len) { std::unique_lock<std::mutex> _lock(_mtx); _cvp.wait(_lock, [&] {return true == run ? (_q.size() < _size) : true; }); if (false == run) return; if (v[wr].capacity() < (len+ sizeof(int))) { v[wr].resize(len*1.2); } char *dataPtr =( char *) &(v[wr][0]); *(int*)dataPtr = len; memcpy(dataPtr+sizeof(int),t,len); _q.emplace_back(dataPtr); wr = ++wr%_size; //std::cout << std::this_thread::get_id() << ":[p]" << static_cast<const void *>(dataPtr) << "[size]:" << _q.size() << std::endl; _cvc.notify_all(); }; int c(std::vector<char> &t) { std::unique_lock<std::mutex> _lock(_mtx); _cvc.wait(_lock, [&] {return true == run ? (_q.size() > 0) : true; }); if (false == run) return NULL; char* dataPtr = _q.front(); int datalen = *(int*)dataPtr; if (t.capacity()<(datalen+sizeof(int))) { t.resize(datalen*1.2); } memcpy(&t[0], dataPtr + sizeof(int), datalen); //std::cout << std::this_thread::get_id() << ":[c]" << (const void *)(dataPtr) << "[size]:" << _q.size() << std::endl; _q.pop_front(); _cvp.notify_all(); return datalen; }; int size() { return _q.size(); }; void stop() { run = false; _cvp.notify_all(); _cvc.notify_all(); } void start() { run = true; } private: //环形vector控制 int wr = 0; bool run = true; int _size; std::unique_ptr<std::vector<unsigned char>[]> v; std::deque<char *> _q; std::mutex _mtx; std::condition_variable _cvp; std::condition_variable _cvc; }; int main(){ pc dqRead(3); std::thread ([&] { char * w = (char*)malloc(1024); while (true) { dqRead.p(w,10); } }).detach(); std::thread ([&] { std::vector<unsinged char> v;while (true) { int len = dqRead.c(v); } }).detach(); }

 

posted on 2020-07-21 17:41  lgy514  阅读(151)  评论(0编辑  收藏  举报