i have 3 files one main.cpp, functions.cpp, and a header.h
im using
#include<fstream>
in the main.cpp and in the functions.cpp but im not sure where to define the ofstream datatype in, so that the main.cpp and the function.cpp share the same ofstream variable.
where do i put this "ofstream outf;" between the 3 files
main.cpp
#include <fstream>
#include "cs.h"
using namespace std;
ofstream outf;
int main ()
{
outf.open("Results.txt");
/*for (int i = 0;i < 500;i++ )
{
int random = rand() %8;
switch (random)
{
case 0 : reader1();
break;
case 1 : reader2();
break;
case 2 : reader3();
break;
case 3 : reader4();
break;
case 4 : reader5();
break;
case 5 : writer1();
break;
case 6 : writer2();
break;
case 7 : writer3();
break;
}
}*/
test();
outf.close();
return 0;
system("pause");
}
functions.cpp
#include <fstream>
#include "cs.h"
using namespace std;
int mutex = 1;
int wrt = 1;
int readcount=0;
int writecount=0;
void test()
{
outf << "@@@@@@@@@@@@@@@@@@@";
}
void reader1()
{
outf << "Reader1 wants to access Critical Section";
P(mutex);
readcount ++;
if(readcount ==0)
{
outf << "Reader1 is the first and only reader";
P(wrt);
}
while(readcount>=3);
outf<<"Reader1 is entering the Critical Section";
V(mutex);
// Crictal Section
outf<<"Reader1 is inside the Critical Section";
if(readcount>=1)
{
outf << "Reader1 sees "<<readcount<<" Readers inside the Critical Section";
}
if(readcount>=4)
{
outf << "PANIC:Reader1 sees four or more Readers";
}
if (writecount>=1)
{
outf << "PANIC:Reader1 sees a Writer";
}
//Crictal Section
P(mutex);
readcount --;
if (readcount==0)
{
V(wrt);
outf << "Room is empty after Reader1 leaves";
}
outf << "Reader1 is exitting the Critical Section";
V(mutex);
}
void writer1()
{
while (true )
{
outf <<" Writer1 wants to access the Critical Section";
writecount++;
P(wrt);
outf << "Writer1 is entering the Critical Section";
//Critical Section
outf << "Reader1 is inside the Critical Section";
if(readcount>=1)
{
outf << "PANIC:Writer1 found a Reader inside the Critical Section";
}
if(writecount>=2)
{
outf << "PANIC:Writer1 found an another Writer inside the Critical Section";
}
//Critical Section
V(wrt);
writecount--;
outf << "Writer1 has left the Critical Section";
}
}
void P( int a)//Wait
{
while(a<=0);
a--;
}
void V(int a)//Signal
{
a++;
}
bool testandset(bool *target)
{
bool rv = *target;
*target = true;
return rv;
}
header.h
#ifndef CS_H
#define CS_H
void reader1();
void reader2();
void reader3();
void reader4();
void reader5();
void writer1();
void writer2();
void writer3();
void P(int);//wait
void V(int);//signal
bool testandset(bool);
void test();
#endif