[英]Manage shared variable in multithreading application
我设计了一个示例多线程应用程序,在该程序中,我使用循环缓冲区在一个线程中读取一个文件(是否检查是否isfull
,并通过检查缓冲区isEmpty
是否将相同的缓冲区写入输出文件。
我的问题是,第一个线程首先完成其执行,以便第二个线程获取缓冲区中的剩余数据,因此输出错误。
码:
/* 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");
}
请提出共享缓冲区访问的任何解决方案。
这里的一个主要问题是您使用静态成员变量,但是除了在构造函数中之外,不要初始化它们,并且由于您从未实际构造该类的实例,因此不会调用该构造函数。
这意味着当您使用静态成员变量时,它们包含不确定的值(即,它们的值似乎是随机的),您将调用未定义的行为 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.