我设计了一个示例多线程应用程序,其中我使用循环缓冲区在一个线程中读取一个文件,并且不检查isfull
,也使用检查缓冲区isEmpty
将相同的缓冲区写入输出文件。 / p>
我的问题是第一个线程首先完成其执行,以便第二个线程在缓冲区中获取剩余数据,因此输出错误。
代码:
/* Circular Queues */
//#include<mutex.h>
#include <iostream>
using namespace std;
#include<windows.h>
const int chunk = 512; //buffer read data
const int MAX = 2*chunk ; //queue size
unsigned int Size ;
FILE *fpOut;
FILE *fp=fopen("Test_1K.txt","rb");
//class queue
class cqueue
{
public :
static int front,rear;
static char *a;
cqueue()
{
front=rear=-1;
a=new char[MAX];
}
~cqueue()
{
delete[] a;
}
};
int cqueue::front;
int cqueue::rear;
char* cqueue::a;
DWORD WINAPI Thread1(LPVOID param)
{
int i;
fseek(fp,0,SEEK_END);
Size=ftell(fp); //Read file size
cout<<"\nsize is"<<Size;
rewind(fp);
for(i=0;i<Size;i+=chunk) //read data in chunk as buffer half size
{
while((cqueue::rear==MAX-1)); //wait until buffer is full?
if((cqueue::rear>MAX-1))
cqueue::rear=0;
else{
fread(cqueue::a,1,chunk,fp); //read data from in buffer
cqueue::rear+=chunk; //increment rear pointer of queue to indicate buffer is filled up with data
if((cqueue::front==-1))
cqueue::front=0; //update front pointer value to read data from buffer in Thread2
}
}
fclose(fp);
cout<<"\nQueue write completed\n";
return 0;
}
DWORD WINAPI Thread2(LPVOID param)
{
for(int j=0;j<Size;j+=chunk)
{
while((cqueue::front==-1)); //wait until buffer is empty
cqueue::front+=chunk; //update front pointer after read data from queue
fwrite(cqueue::a,1,chunk,fpOut); //write data file
if((cqueue::front==MAX-1))
cqueue::front=0; //update queue front pointer when it reads upto queue Max size
}
fclose(fpOut);
cout<<"\nQueue read completed\n";
return 0;
}
void startThreads()
{
DWORD threadIDs[2];
HANDLE threads[2];
fpOut=fopen("V-1.7OutFile.txt","wb");
threads[0] = CreateThread(NULL,0,Thread1,NULL,0,&threadIDs[0]);
threads[1] = CreateThread(NULL,0,Thread2,NULL,0,&threadIDs[1]);
if(threads[0] && threads[1])
{
printf("Threads Created.(IDs %d and %d)",threadIDs[0],threadIDs[1]);
}
}
void main()
{
cqueue c1;
startThreads();
system("pause");
}
请建议任何共享缓冲区访问的解决方案。
答案 0 :(得分:1)
这里的一个主要问题是你使用静态成员变量,但是从不在构造函数中初始化它们,并且因为你从未实际构造类的实例,所以不会调用构造函数。
这意味着当您使用静态成员变量时,它们包含不确定的值(即它们的值看似随机),您调用未定义的行为。