body, table{font-family: 微软雅黑; font-size: 10pt}
table{border-collapse: collapse; border: solid gray; border-width: 2px 0 2px 0;}
th{border: 1px solid gray; padding: 4px; background-color: #DDD;}
td{border: 1px solid gray; padding: 4px;}
tr:nth-child(2n){background-color: #f8f8f8;}

基于对象:
Noncopyable.h MutexLock.h
#ifndef __NONCOPYABLE_H__
#define __NONCOPYABLE_H__
#include<iostream>
using namespace std;
namespace meihao
{
        class Noncopyable
        {
                protected:
                        Noncopyable(){}
                        ~Noncopyable(){}
                private:
                        Noncopyable(const Noncopyable&);
                        Noncopyable& operator=(const Noncopyable&);
        };
};
#endif

#ifndef __MUTEXLOCK_H__
#define __MUTEXLOCK_H__
#include<iostream>
#include"Noncopyable.h"
#include<pthread.h>
using namespace std;
namespace meihao
{
        class MutexLock:private Noncopyable
        {
                public:
                        MutexLock();
                        ~MutexLock();
                        void lock();
                        void unlock();
                        pthread_mutex_t* getMutexPtr();
                private:
                        pthread_mutex_t _mutex;
        };
};
#endif

Condition.h Buffer.h
#ifndef __CONDITION_H__
#define __CONDITION_H__
#include<iostream>
#include"Noncopyable.h"
#include<pthread.h>
using namespace std;
namespace meihao
{
        class MutexLock;
        class Condition:private Noncopyable
        {
                public:
                        Condition(MutexLock& mutex):_mutex(mutex)
                        {
                                pthread_cond_init(&_cond,NULL);
                        }
                        ~Condition();
                        void wait();
                        void notify();
                        void notifyall();
                private:
                        pthread_cond_t _cond;
                        MutexLock& _mutex;
        };
};
#endif

#ifndef __BUFFER_H__
#define __BUFFER_H__
#include<iostream>
#include"MutexLock.h"
#include"Condition.h"
#include<queue>
using namespace std;
namespace meihao
{
        typedef int DataType;
        class Buffer
        {
                public:
                        Buffer(int);
                        ~Buffer();
                        void push(DataType);
                        DataType pop();
                        bool full();
                        bool empty();
                private:
                        MutexLock _mutex;
                        Condition _notFull;
                        Condition _notEmpty;
                        queue<DataType> _que;
                        int _size;
        };
};
#endif

thread.h MutexLock.cpp
#ifndef __THREAD_H__
#define __THREAD_H__
#include<iostream>
#include<pthread.h>
#include<functional>
#include"Noncopyable.h"
using namespace std;
namespace meihao
{
        typedef std::function<void()> ThreadCallback;
        class Thread:private Noncopyable
        {
                public:
                        Thread(ThreadCallback cb):_pthId(0),_isRunning(false),_cb(cb){}
                        ~Thread();
                        void start();
                        void join();
                        static void* threadFunc(void*);
                private:
                        pthread_t _pthId;
                        bool _isRunning;
                        ThreadCallback _cb;
        };
};
#endif

#include<iostream>
#include"MutexLock.h"
using namespace std;
namespace meihao
{
        MutexLock::MutexLock()
        {
                pthread_mutex_init(&_mutex,NULL);
        }
        MutexLock::~MutexLock()
        {
                pthread_mutex_destroy(&_mutex);
        }
        void MutexLock::lock()
        {
                pthread_mutex_lock(&_mutex);
        }
        void MutexLock::unlock()
        {
                pthread_mutex_unlock(&_mutex);
        }
        pthread_mutex_t* MutexLock::getMutexPtr()
        {
                return &_mutex;
        }
};

Condition.cpp Buffer.cpp
#include<iostream>
#include"Condition.h"
#include"MutexLock.h"
using namespace std;
namespace meihao
{
        Condition::~Condition()
        {
                pthread_cond_destroy(&_cond);
        }
        void Condition::wait()
        {
                pthread_cond_wait(&_cond,_mutex.getMutexPtr());
        }
        void Condition::notify()
        {
                pthread_cond_signal(&_cond);
        }
        void Condition::notifyall()
        {
                pthread_cond_broadcast(&_cond);
        }
};

#include<iostream>
#include"Buffer.h"
using namespace std;
namespace meihao
{
        Buffer::Buffer(int size):_mutex(),_notFull(_mutex),_notEmpty(_mutex),_size(size){}
        Buffer::~Buffer(){}
        bool Buffer::full()
        {
                return _size == _que.size();
        }
        bool Buffer::empty()
        {
                return _que.size() == 0;  // 这个地方脑子坏了,写成_size == 0;  导致后面pop等待作废
        }
        void Buffer::push(DataType value)
        {
                _mutex.lock();
                if(full())
                {
                        _notFull.wait();  // 等待条件变量,队列没有满,唤醒
                }
                _que.push(value);
                cout<<"prodece a num "<<value<<endl;
                _notEmpty.notify();  // 有一个元素进队列,_notEmpty的条件变量满足
                _mutex.unlock();
        }
        DataType Buffer::pop()
        {
                _mutex.lock();
                if(empty())
                {
                        _notEmpty.wait();  // 等待不空的条件变量_notEmpty满足
                }
                DataType tmp = _que.front();
                _que.pop();
                cout<<"consumer a num "<<tmp<<endl;
                _notFull.notify();
                _mutex.unlock();
                return tmp;
        }
};

thread.cpp test.cpp
#include<iostream>
#include"Thread.h"
using namespace std;
namespace meihao
{
        Thread::~Thread()
        {
                pthread_detach(_pthId);
        }
        void Thread::start()
        {
                pthread_create(&_pthId,NULL,&Thread::threadFunc,this);  // 调用成员函数的this指针也要传递过去
                _isRunning = true;
        }
        void Thread::join()
        {
                if(_isRunning)
                {
                        pthread_join(_pthId,NULL);
                        _isRunning = false;
                }
        }
        void* Thread::threadFunc(void* arg)
        {
                Thread* pthread = static_cast<Thread*> (arg);
                if(NULL!=pthread)
                {
                        pthread->_cb();
                }
        }
};

#include<iostream>
#include"Buffer.h"
#include<time.h>
#include<unistd.h>
#include"Thread.h"
using namespace std;
struct Producer
{
        void produce(meihao::Buffer& buffer)
        {
                ::srand(time(NULL));
                int i = 0;
                while(i<5)
                {
                        int num = rand()%100;
                        buffer.push(num);
                        //cout<<"prodece a num "<<num<<endl;  // 放在这里可能导致不一致了
                        sleep(1);
                        i++;
                }
        }
};
struct Consumer
{
        void consumer(meihao::Buffer& buffer)
        {
                int i = 0;
                while(i<5)
                {
                        int num = buffer.pop();
                        //cout<<"consumer a num "<<num<<endl;
                        sleep(2);
                        i++;
                }
        }
};
int main()
{
        Producer p1;
        Consumer c1;
        meihao::Buffer buffer(5);
        meihao::Thread produceThread(bind(&Producer::produce,&p1,ref(buffer))); 
        //生产者线程
        meihao::Thread consumThread(bind(&Consumer::consumer,&c1,ref(buffer)));
        //消费者线程
        produceThread.start();
        consumThread.start();
        produceThread.join();
        consumThread.join();
        return 0;
}

面向对象:
Nocopyable.h MutexLock.h
#ifndef __NONCOPYABLE_H__
#define __NONCOPYABLE_H__
#include<iostream>
using namespace std;
namespace meihao
{
        class Noncopyable
        {
                protected:
                        Noncopyable(){}
                        ~Noncopyable(){}
                private:
                        Noncopyable(const Noncopyable&);
                        Noncopyable& operator=(const Noncopyable&);
        };
};
#endif

#ifndef __MUTEXLOCK_H__
#define __MUTEXLOCK_H__
#include<iostream>
#include"Noncopyable.h"
#include<pthread.h>
using namespace std;
namespace meihao
{
        class MutexLock:private Noncopyable
        {
                public:
                        MutexLock();
                        ~MutexLock();
                        void lock();
                        void unlock();
                        pthread_mutex_t* getMutexPtr();
                private:
                        pthread_mutex_t _mutex;
        };
};
#endif

Condition.h Buffer.h
#ifndef __CONDITION_H__
#define __CONDITION_H__
#include<iostream>
#include"Noncopyable.h"
#include<pthread.h>
using namespace std;
namespace meihao
{
        class MutexLock;
        class Condition:private Noncopyable
        {
                public:
                        Condition(MutexLock& mutex):_mutex(mutex)
                        {
                                pthread_cond_init(&_cond,NULL);
                        }
                        ~Condition();
                        void wait();
                        void notify();
                        void notifyall();
                private:
                        pthread_cond_t _cond;
                        MutexLock& _mutex;
        };
};
#endif

#ifndef __BUFFER_H__
#define __BUFFER_H__
#include<iostream>
#include"MutexLock.h"
#include"Condition.h"
#include<queue>
using namespace std;
namespace meihao
{
        typedef int DataType;
        class Buffer
        {
                public:
                        Buffer(int);
                        ~Buffer();
                        void push(DataType);
                        DataType pop();
                        bool full();
                        bool empty();
                private:
                        MutexLock _mutex;
                        Condition _notFull;
                        Condition _notEmpty;
                        queue<DataType> _que;
                        int _size;
        };
};
#endif

Thread.h ProduceThread.h
#ifndef __THREAD_H__
#define __THREAD_H__
#include<iostream>
#include"Noncopyable.h"
#include<pthread.h>
using namespace std;
namespace meihao
{
        class Thread:private Noncopyable
        {
                public:
                        Thread();
                        void start();
                        void join();
                        virtual void run() = 0;
                        virtual ~Thread();
                        static void* threadFunc(void*);
                private:
                        pthread_t _pthId;
                        bool _isRunning;
        };
};
#endif

#ifndef __PRODUCETHREAD_H__
#define __PRODUCETHREAD_H__
#include<iostream>
#include"thread.h"
#include"Buffer.h"
using namespace std;
namespace meihao
{
        class ProduceThread:public Thread
        {
                public:
                        ProduceThread(Buffer& buff):_buff(buff){}
                        void run();
                private:
                        Buffer& _buff;
        };
};
#endif

ConsumerThread.h thread.cpp
#ifndef __CONSUMERTHREAD_H__
#define __CONSUMERTHREAD_H__
#include<iostream>
#include"thread.h"
#include"Buffer.h"
using namespace std;
namespace meihao
{
        class ConsumerThread:public Thread
        {
                public:
                        ConsumerThread(Buffer& buff):_buff(buff){}
                        void run();
                private:
                        Buffer& _buff;
        };
};
#endif

#include<iostream>
#include"thread.h"
using namespace std;
namespace meihao
{
        Thread::Thread():_pthId(0),_isRunning(false){}
        void Thread::start()
        {
                pthread_create(&_pthId,NULL,&Thread::threadFunc,this);
                _isRunning = true;
        }
        void Thread::join()
        {
                if(_isRunning)
                {
                        pthread_join(_pthId,NULL);
                }
        }
        Thread::~Thread()
        {
                pthread_detach(_pthId);
        }
        void* Thread::threadFunc(void* arg)
        {
                Thread* pthread = static_cast<Thread*> (arg);
                if(NULL!=pthread)
                {
                        pthread->run();
                }
        }
};

ProduceThread.cpp ConsumerThread.cpp
#include<iostream>
#include"ProduceThread.h"
#include<time.h>
#include<unistd.h>
using namespace std;
namespace meihao
{
        void ProduceThread::run()
        {
                ::srand(time(NULL));
                int i = 0;
                while(i<5)
                {
                        int num = ::rand()%100;
                        _buff.push(num);
                        cout<<"produce a num "<<num<<endl;
                        sleep(1);
                        i++;
                }
        }
};
#include<iostream>
#include"ConsumerThread.h"
#include<unistd.h>
using namespace std;
namespace meihao
{
        void ConsumerThread::run()
        {
                int i = 0;
                while(i<5)
                {
                        int num = _buff.pop();
                        cout<<"Consumer a num "<<num<<endl;
                        sleep(2);
                i++;
                }
        }
};
MutexLock.cpp Condition.cpp
#include<iostream>
#include"MutexLock.h"
using namespace std;
namespace meihao
{
        MutexLock::MutexLock()
        {
                pthread_mutex_init(&_mutex,NULL);
        }
        MutexLock::~MutexLock()
        {
                pthread_mutex_destroy(&_mutex);
        }
        void MutexLock::lock()
        {
                pthread_mutex_lock(&_mutex);
        }
        void MutexLock::unlock()
        {
                pthread_mutex_unlock(&_mutex);
        }
        pthread_mutex_t* MutexLock::getMutexPtr()
        {
                return &_mutex;
        }
};
#include<iostream>
#include"Condition.h"
#include"MutexLock.h"
using namespace std;
namespace meihao
{
        Condition::~Condition()
        {
                pthread_cond_destroy(&_cond);
        }
        void Condition::wait()
        {
                pthread_cond_wait(&_cond,_mutex.getMutexPtr());
        }
        void Condition::notify()
        {
                pthread_cond_signal(&_cond);
        }
        void Condition::notifyall()
        {
                pthread_cond_broadcast(&_cond);
        }
};
Buffer.cpp test.cpp
#include<iostream>
#include"Buffer.h"
using namespace std;
namespace meihao
{
        Buffer::Buffer(int size):_mutex(),_notFull(_mutex),_notEmpty(_mutex),_size(size){}
        Buffer::~Buffer(){}
        bool Buffer::full()
        {
                return _size == _que.size();
        }
        bool Buffer::empty()
        {
                return _que.size() == 0;  // 这个地方脑子坏了,写成_size == 0;  导致后面pop等待作废
        }
        void Buffer::push(DataType value)
        {
                _mutex.lock();
                if(full())
                {
                        _notFull.wait();  // 等待条件变量,队列没有满,唤醒
                }
                _que.push(value);
                _notEmpty.notify();  // 有一个元素进队列,_notEmpty的条件变量满足
                _mutex.unlock();
        }
        DataType Buffer::pop()
        {
                _mutex.lock();
                if(empty())
                {
                        _notEmpty.wait();  // 等待不空的条件变量_notEmpty满足
                }
                DataType tmp = _que.front();
                _que.pop();
                _notFull.notify();
                _mutex.unlock();
                return tmp;
        }
};
#include<iostream>
#include"ProduceThread.h"
#include"ConsumerThread.h"
using namespace std;
int main()
{
        meihao::Buffer buffer(10);
        meihao::Thread* produce = new meihao::ProduceThread(buffer);
        meihao::Thread* consumer = new meihao::ConsumerThread(buffer);
        produce->start();
        consumer->start();
        produce->join();
        consumer->join();
        delete produce;
        delete consumer;
        return 0;
}

生产者与消费者问题,C++利用bind基于对象实现与面向对象实现的更多相关文章

  1. JavaScript基于对象编程

    js面向对象特征介绍 javascript是一种面向(基于)对象的动态脚本语言,是一种基于对象(Object)和事件驱动(EventDirven)并具有安全性能的脚本语言.它具有面向对象语言所特有的各 ...

  2. 利用反射快速给Model实体赋值 使用 Task 简化异步编程 Guid ToString 格式知多少?(GUID 格式) Parallel Programming-实现并行操作的流水线(生产者、消费者) c# 无损高质量压缩图片代码 8种主要排序算法的C#实现 (一) 8种主要排序算法的C#实现 (二)

    试想这样一个业务需求:有一张合同表,由于合同涉及内容比较多所以此表比较庞大,大概有120多个字段.现在合同每一次变更时都需要对合同原始信息进行归档一次,版本号依次递增.那么我们就要新建一张合同历史表, ...

  3. java 多线程 22 :生产者/消费者模式 进阶 利用await()/signal()实现

    java多线程15 :wait()和notify() 的生产者/消费者模式 在这一章已经实现了  wait/notify 生产消费模型 利用await()/signal()实现生产者和消费者模型 一样 ...

  4. 利用BlockingCollection实现生产者和消费者队列,实现写文本

    最近开发几个小项目,需要把结果写到txt文件里面,并且按照时间进行分文件,由于对于效率要求较高,所以采用 生产者和消费者 模型来进行写出文本,线程中只需要添加队列就立即返回,而不需要等待写文件的时间 ...

  5. 基于kafka_2.11-2.1.0实现的生产者和消费者代码样例

    1.搭建部署好zookeeper集群和kafka集群,这里省略. 启动zk: bin/zkServer.sh start conf/zoo.cfg. 验证zk是否启动成功: bin/zkServer. ...

  6. 生产者,消费者,CDN

    1 生产者消费者模型应用场景及优势? 什么是生产者消费者模型 在 工作中,大家可能会碰到这样一种情况:某个模块负责产生数据,这些数据由另一个模块来负责处理(此处的模块是广义的,可以是类.函数.线程.进 ...

  7. RabbitMQ四:生产者--队列--消费者

    AMQP协议的梳理和名词解析  建议先把上篇AMQP协议先看一遍,理解一下,由于用XMind绘图,电脑屏幕比较小,不能截取全部,如果想要全图和源代码,请下面留言....... 可以点击图片,打开到新的 ...

  8. Python爬虫的经典多线程方式,生产者与消费者模型

    在之前的文章当中我们曾经说道,在多线程并发的场景当中,如果我们需要感知线程之间的状态,交换线程之间的信息是一件非常复杂和困难的事情.因为我们没有更高级的系统权限,也没有上帝视角,很难知道目前运行的状态 ...

  9. 第3月第2天 find symbolicatecrash 生产者-消费者 ice 引用计数

    1.linux find export find /Applications/Xcode.app/ -name symbolicatecrash -type f export DEVELOPER_DI ...

随机推荐

  1. 监听浏览器种类,并区分safari和chrom浏览器

    //判断浏览器种类函数-处理兼容性 function myBrowser(){ var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 va ...

  2. nodejs中function*、yield和Promise的示例

    var co = require("co"); var fs = require("fs"); function cusReadFile(fileName) { ...

  3. thinkphp5的Auth权限认证实战

    thinkphp5的Auth权限认证实战 一.总结 一句话总结:基于角色的权限管理(真正做一遍,就会发现很简单,不然一直都是半懂不懂的) 角色 权限 真正做一遍,就会发现很简单,不然一直都是半懂不懂的 ...

  4. Python 编程快速上手 第八章总结

    在下面函数中的()中,可为相对路径,也可为绝对路径. 获知当前目录,改变当前目录,查看当前目录 更改当前目录:os.getcwd() 改变当前目录:os.chdir() 查看当前目录:os.listd ...

  5. spring boot ----> 和mybatis。。。

    环境: centos6.8,jdk1.8.0_172,maven3.5.4,spring boot1.5.15 1.使用maven命令:mvn dependency:tree查看mybatis-spr ...

  6. BGP - 2,BGP报文和BGP状态

    1,BGP报文      Open:建邻居,交换version.AS号.holdtime.BGP identifier(即RouterID).可选参数长度.可选参数.      Keepalive:保 ...

  7. LeetCode--020--括号匹配(java版)

    给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. 注意空字符串可被认 ...

  8. PHP字符串函数小结

    1. strlen:获得字符串长度 2. substr:字符串截取函数 格式:string substr ( string $string , int $start [, int $length ] ...

  9. dijkstra优化

    1, 桶优化最短路, 时间复杂度$O(m+n)$, 空间$O(C)$, $C$为最短路长度 const int N = 1e6+10; int n, m; struct _ {int to,w;}; ...

  10. dsu on tree练习

    dsu on tree主要是处理一些有根树子树询问的操作, 作用与点分治和线段树合并类似. 一般无根树询问所有树链信息的直接就点分了, 有根树的话一般用线段树合并或dsu on tree, 线段树合并 ...