C++ 流重写堆栈变量的方法

C++ 流重写堆栈变量的方法,c++,netbeans,g++,C++,Netbeans,G++,我正在为操作系统类编写一个“线程池”程序。基本上,文件是从tar文件中提取出来的,并使用5个线程池写入磁盘。这是我的线程代码 #include <iostream> #include <cstdlib> using namespace std; vector<Header*> headers; vector<string> fileBlocks; void* writeExtractedFiles(void* args) { bool h

我正在为操作系统类编写一个“线程池”程序。基本上,文件是从tar文件中提取出来的,并使用5个线程池写入磁盘。这是我的线程代码

#include <iostream>
#include <cstdlib>
using namespace std;

vector<Header*> headers;
vector<string> fileBlocks;
void* writeExtractedFiles(void* args)
{
    bool hasFilesLeft = true;
    ofstream outputFile;
    while(hasFilesLeft)
    {
        pthread_mutex_lock(&mutex);
        if(headers.size() != 0)
        {
            Header* hdr = headers.back();
            headers.pop_back();
            string fileBytes = fileBlocks.back();
            fileBlocks.pop_back();
            pthread_mutex_unlock(&mutex);

            outputFile.open(hdr->fileName.c_str(), ios::app);
            outputFile.rdbuf()->pubsetbuf(0,0);
            fileBytes = fileBytes.substr(0, hdr->fileSize);
            outputFile.put('0');
            outputFile.close();
            // This is a dummy object to check if the values are corrupted
            Header* test0 = headers.back();
            cout << "GRAWWR!";
            //chown(hdr->fileName.c_str(), hdr->userId, hdr->groupId);
            //chmod(hdr->fileName.c_str(), hdr->fileMode);
        }
        else
        {
            // We're done!
            hasFilesLeft = false;
            pthread_mutex_unlock(&mutex);
        }
    }
}
#包括
#包括
使用名称空间std;
向量头;
矢量文件块;
void*writeExtractedFiles(void*args)
{
bool hasFilesLeft=true;
流输出文件;
while(左)
{
pthread_mutex_lock(&mutex);
if(headers.size()!=0)
{
Header*hdr=headers.back();
headers.pop_back();
string fileBytes=fileBlocks.back();
fileBlocks.pop_back();
pthread_mutex_unlock(&mutex);
open(hdr->fileName.c_str(),ios::app);
outputFile.rdbuf()->pubsetbuf(0,0);
fileBytes=fileBytes.substr(0,hdr->fileSize);
outputFile.put('0');
outputFile.close();
//这是一个虚拟对象,用于检查值是否损坏
Header*test0=headers.back();
cout fileName.c_str(),hdr->userId,hdr->groupId);
//chmod(hdr->fileName.c_str(),hdr->fileMode);
}
其他的
{
//我们完了!
hasFilesLeft=false;
pthread_mutex_unlock(&mutex);
}
}
}
注意到目前为止,我只使用一个线程来测试它。显然,在我的互斥对象之外访问
头文件
向量会对多个线程产生反作用

问题是,
test0
的值都是乱七八糟的,
fileName
的值是超高的数字,而且毫无意义。似乎出于某种原因我正在覆盖堆栈变量。当我注释掉
outputFile.close()时然后我的变量值不会改变,但当我保留它时,无论我是否真的将内容写入文件,事情都会变得不稳定。我知道我一定错过了什么。我试着完全去掉缓冲区,在不同的地方写文件,任何我能想到的东西。有什么建议吗


(我正在Windows机器上测试它,但它是为Linux制作的)

首先,显而易见。你在访问
标题
时,正是你所说的“乱七八糟”的项目在闩锁外面。你这样做有什么特别的原因吗?在打开文件之前你有一个解锁,对吗?@Zelldon我认为那部分很好。在解锁之前,头和文件信息都会从各自的队列中弹出。但文件关闭后的那一行令人沮丧。这是完全没有保护的。好的,谢谢你的回答。。。是的,我同意,那就是sense@WhozCraig-此特定行在互斥外部重复-Header*test0=headers.back();-对我来说也没有任何意义。ReimTime-这里的“测试”是什么?