码迷,mamicode.com
首页 > 其他好文 > 详细

生产者与消费者的一个简单例子

时间:2014-06-24 11:29:19      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   com   get   

  • 生产者

#include<fstream>

#include<iostream>

#include<Windows.h>

 

using namespace std;

 

int main(void)

{

    ofstream out;

 

    const char ch = ‘*‘;

    long long k = 0;

    DWORD64 time = GetTickCount64();

    while (true)

    {

        if (GetTickCount64() - time > 5000)

        {

            out.open("1", ios::binary | ios::out | ios::app);

            ++k;

            out.write((char*) (&ch), sizeof(char));

            out.close();

            time = GetTickCount64();

            cout << "product " << k << endl;

        }    

    }

    return 0;

}

 

  • 消费者

#include<iostream>

#include<fstream>

#include<Windows.h>

 

using namespace std;

 

int main(void)

{

    ifstream in("1", ios::binary | ios::in);

    ofstream consumer("2", ios::binary | ios::out);

    while (!in)

    {

        cout << "producter is not readly!" << endl;

        Sleep(2000);

        in.open("1", ios::binary | ios::in);

    }

    long long k = 1;

    char c;

    while (true)

    {

        while (in.eof()||in.peek()!=‘*‘)

        {

            cout << "product is empty!" << endl;

            in.close();

            Sleep(1790);

            in.open("1", ios::binary | ios::in);

            in.ignore(k - 1);

        }

        in.read((char *) (&c), sizeof(char));

        in.close();

        consumer << c << flush;

        cout << "consumer " << k << endl;

        k++;

        Sleep(2000);

        in.open("1", ios::binary | ios::in);

        in.ignore(k-1);

    }

    return 0;

}

  • 运行效果

bubuko.com,布布扣

生产者与消费者的一个简单例子,布布扣,bubuko.com

生产者与消费者的一个简单例子

标签:style   blog   http   color   com   get   

原文地址:http://www.cnblogs.com/xiahualin/p/3805291.html

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