码迷,mamicode.com
首页 > 编程语言 > 详细

生产者,消费者 多线程

时间:2017-04-25 00:43:03      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:amp   const   cout   log   mutex   using   线程   har   main   

  

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

const size_t SIZE = 10;
using ElemTy = char;
ElemTy arr[SIZE];

size_t begin = 0;
size_t end = 0;

std::mutex prdc_m;
std::mutex cnsm_m;

void produce() {
  for (;;) {
    if ((end + 1) % SIZE != begin) {
      {
        std::lock_guard<std::mutex> lg(prdc_m);
        arr[end] = o;
        end = (end + 1) % SIZE;
        std::cout << "produce and size is " << (end - begin) % SIZE << std::endl;
      }
    }
  }
}

void consume() {
  for (;;) {
    if (begin != end) {
      ElemTy e;
      {
        std::lock_guard<std::mutex> lg(cnsm_m);
        e = arr[begin];
        begin = (begin + 1) % SIZE;
        std::cout << "consume and size is " << (end - begin) % SIZE << std::endl;
      }
    }
  }
}

int main() {
  std::vector<std::thread> vc;
  std::vector<std::thread> vp;
  for (int i = 0; i < 10; ++i) {
    vc.push_back(std::thread(consume));
  }
  for (int i = 0; i < 10; ++i) {
    vp.push_back(std::thread(produce));
  }

  for (auto &t : vc) {
    t.join();
  }

  for (auto &t : vp) {
    t.join();
  }

  return 0;
}

 

生产者,消费者 多线程

标签:amp   const   cout   log   mutex   using   线程   har   main   

原文地址:http://www.cnblogs.com/jjtx/p/6759605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!