Hi!
I have design one c++ multithreading application (first time) in which one thread does following task: it read values from file & insert into dynamic queue. Second thread does read values from queue and write into output file; Sometimes task is done as i wish like 'Queue is write complete'(output of first thread) and after 'Queue read completed'(output of second thread),but sometimes it behaves abnormal means it shows output of second thread & then output of first thread;also sometimes output of first thread,not second and wiseversa.
Below i copied my code,please suggest any changes required for it.
Also my doubt:Is that operating system monitors these threads,so it shows different output?
#include <iostream>
using namespace std;
#include<windows.h>
const int MAX = 2*1048576;
int Size ;
HANDLE hThread1,hThread2;
DWORD dwID1,dwID2;
DWORD Thread1(LPVOID param);
DWORD Thread2(LPVOID param);
FILE *fp,*fpOut;
class cqueue
{
public :
static int front,rear;
static int *a; cqueue()
{
front=rear=-1;
a=new int[MAX];
}
~cqueue()
{
delete[] a;
}
static void insertWithAck(char);
static int deletionWithAck();
};
int cqueue::front;
int cqueue::rear;
int* cqueue::a;
void cqueue :: insertWithAck(char val)
{
while((rear==MAX-1) || (rear+1==front)) ;
if(rear==MAX-1)
rear=0;
else
rear++;
a[rear]=val;
if(front==-1)
front=0;
}
int cqueue :: deletionWithAck()
{
char k;
while(front== -1);
k=a[front];
if(front==rear)
front=rear=-1;
else
{
if(front==MAX-1)
front=0;
else
front++;
}
return k;
}
DWORD Thread1(LPVOID param)
{
int i,val;
fp=fopen("1MB_TEST_FILE.txt","rb");
fseek(fp,0,SEEK_END);
Size=ftell(fp);
rewind(fp);
for(i=0;i<Size;i++){
fread(&val,1,1,fp);
cqueue::insertWithAck(val);
}
fclose(fp);
cout<<"Queue write completed\n";
return 0;
}
DWORD Thread2(LPVOID param)
{
fpOut=fopen("OutFile.txt","wb");
char retVal;
for(int i=0;i<Size;i++){
retVal=cqueue::deletionWithAck();
fwrite(&retVal,1,1,fpOut);
}
fclose(fpOut);
cout<<"Queue read completed\n";
return 0;
}
void main()
{
cqueue c1;
hThread1= CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Thread1,NULL,0,&dwID1);
hThread2= CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Thread2,NULL,0,&dwID2);
system("pause")
}