2014-02-13 236 views
0

我設計了一個示例多線程應用程序,其中我使用循環緩衝區在一個線程中讀取一個文件,檢查是否爲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"); 
} 

請提出的共享緩衝存取的任何解決方案。

回答

1

這裏的一個主要問題是,你使用靜態成員變量,但從來沒有初始化它們除了在構造函數,因爲你從來沒有真正構建類的構造函數將不會被調用的實例。

這意味着當你使用靜態成員變量時,它們包含不確定的值(即它們的值看起來是隨機的),你調用未定義的行爲

+0

如何訪問變量線程? –

+0

謝謝!我刪除靜態變量聲明。 –

+0

@SumanPandey就像你現在要做的,但首先你需要初始化它們(你現在不這樣做),然後你應該使用例如互斥體來保護它們。 –