- 生产者
#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;
}
- 运行效果
生产者与消费者的一个简单例子