簡體   English   中英

在多線程應用程序中管理共享變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM