//http://www.baptiste-wicht.com/2012/04/c11-concurrency-tutorial-advanced-locking-and-condition-variables/
//g++ -std=c++11 testboundered.cpp -o testboundered.exe
#include <mutex>
#include <condition_variable>
#include <iostream>

using namespace std ;

struct BoundedBuffer { 
    int* buffer; 
    int capacity; 
    int front; 
    int rear; 
    int count; 
    std::mutex lock; 
    std::condition_variable not_full; 
    std::condition_variable not_empty; 
    BoundedBuffer(int capacity=200) : capacity(capacity), front(0), rear(0), count(0) { 
        buffer = new int[capacity]; 
    }
 void SetCapacity(int icapacity)
 {
        if(buffer != nullptr)
  {
      //cout << "delete old buffer " << endl ;
      delete[]  buffer ;
  }
  capacity = icapacity ;
  buffer = new int[capacity]; 
 }
    ~BoundedBuffer(){ 
        delete[] buffer; 
    } 
    void deposit(int data){ 
        std::unique_lock<std::mutex> l(lock); 
        //not_full.wait(l, [&count, &capacity](){return count != capacity; }); 
  not_full.wait(l, [this](){return count != capacity; }); 
        buffer[rear] = data; 
        rear = (rear + 1) % capacity; 
        ++count; 
        not_empty.notify_one(); 
    } 
    int fetch(){ 
        std::unique_lock<std::mutex> l(lock); 
        //not_empty.wait(l, [&count](){return count != 0; }); 
  not_empty.wait(l, [this](){return count != 0; }); 
        int result = buffer[front]; 
        front = (front + 1) % capacity; 
        --count;
        not_full.notify_one(); 
        return result; 
    }
};

 

//http://www.baptiste-wicht.com/2012/04/c11-concurrency-tutorial-advanced-locking-and-condition-variables/

#include <iostream>
#include <atomic>
#include <thread>
#include <cstdio>
#include <memory.h>
#include <string.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <chrono>
#include "bounderbuffer.hpp"

using namespace std ;

BoundedBuffer  DataBuffer(100) ;

void f1()
{
    int iIdx = 0 ;
    while (true)
    {
        DataBuffer.deposit(iIdx) ;
  //printf("(%d) deposit \n",iIdx) ;
  ++iIdx ;
  std::chrono::milliseconds sleepDuration(50); // 50 / 1000 = 0.05 sec
  std::this_thread::sleep_for(sleepDuration);
  //usleep(5000) ;
 }
}

void f2()
{
    int ires = 0 ;
    while (true)
    {
        ires = DataBuffer.fetch() ;
  printf("(%d) fetch \n",ires) ;
  std::chrono::milliseconds sleepDuration(500); //500 / 1000 = 0.5 sec
  std::this_thread::sleep_for(sleepDuration);
 }
}

 

int main()
{
    std::cout << "Hello waiter" << std::endl;
    std::chrono::milliseconds dura( 2000 );
    std::this_thread::sleep_for( dura );
    std::cout << "Waited 2000 ms\n";

    std::thread t1(f1);
    std::thread t2(f2);
    t1.join();
    t2.join(); 
}

 

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()