c++ - 在文件中写入字符数组时出现访问冲突

标签 c++ multithreading pointers ofstream

我正在编写一个小程序,它为主程序完成所有“写入文件”的工作。数据是大小不固定的结构。它们有很多,并且将来会添加新的。 因此,我决定使用 char 数组并将指向这些数组的指针从一个方法传递到另一个方法。

70% 的时间代码按预期运行,但我经常在写入数组时遇到“访问冲突”错误,有时此错误会连续出现几次。我就是找不到模式。

请注意,Execute 在不同的线程上运行。

struct BufferElement
{
  char* ptrData;
  int TotalBytes;
  int StartPosition;
  std::string FileName;
};

class FileThread
{
private:
  std::vector<BufferElement> Queue;
  bool BoolThread;
  std::ofstream writestream;

//This Method calls the "WriteInFile" Method for the first element in the
//Queue and erases it from the vector
void Execute( void )
{
  while( BoolThread )
  {
    if( Queue.size() > 0 )
    {
      if( WriteInFile() )
      {
        delete[] Queue.at( 0 ).ptrData;
        Queue.erase( Queue.begin() );
      }
    }
  }
}

//This Method writes the first Element of the Queue in the file
bool WriteInFile( void )
{
  if( Queue.at(0).ptrData == NULL )
  {
    return true;
  }

  writestream.open( Queue.at(0).FileName.c_str(), std::ios::in |
                       std::ios::out | std::ios::binary );

  if( !writestream.is_open() )
  {
     writestream.close();
     writestream.clear();
     return false;
  }

  writestream.seekp( Queue.at( 0 ).StartPosition );
  writestream.write( Queue.at( 0 ).ptrData, Queue.at( 0 ).TotalBytes );

  writestream.close();
  writestream.clear();

 return true;
}

public:
void EndThread(void)
{
  BoolThread = false;
  for( int i = 0; i < Queue.size(); i++ )
  {
    delete[] Queue.at( i ).ptrData;
  }
}

template< typename T >
void WriteOrder( std::string _FileName, T _Data, int _StartPosition )
{
  BufferElement Temp_BufferElement;
  Temp_BufferElement.TotalBytes = sizeof( _Data );
  Temp_BufferElement.StartPosition = _StartPosition;
  Temp_BufferElement.FileName = _FileName;

  Temp_BufferElement.ptrData = new char[ Temp_BufferElement.TotalBytes ];
  memcpy( Temp_BufferElement.DataPtr, _Data, Temp_BufferElement.TotalBytes );

  Queue.push_back( Temp_BufferElement );
}
};

int main(void)
{
  std::string Path = "..\\Data\\Test.dat";
  FileThread Writer;

  for( int i = 0; i < 1000; i++ )
  {
    char array[] = {'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};
    Writer.WriteOrder( Path, array, i * sizeof( array );
  }

  system("pause");
  Writer.EndThread();
  return 0;
}

如果有人能看一下代码,我会很高兴。也许我只是忽略了一些东西。 我正在使用 Borland Turbo C++ Builder,线程是 vcl 类中的一个对象。

最佳答案

您需要同步对队列的访问。如果您的主线程在工作线程修改队列时写入队列,您可能会崩溃。此外,如果您执行 push_back,数组内存可能会变得无效,而 worker 仍在使用该无效内存。

我也看不到 BoolThread 在哪里初始化或更改。因此,这个示例要么不完整,要么可能表现得很奇怪。

关于c++ - 在文件中写入字符数组时出现访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42411955/

相关文章:

linux - 线程量子 : How to compute it

c++ - 我可以在一个线程中写入变量并在 C++ 中的另一个线程中读取它吗

c - 涉及指针的意外 C 行为

c++ - 将私有(private)方法类成员作为指向函数的指针传递

c++ - 仅由变量标识符组成的表达式类型

c++ - 如果稍后定义返回对象的类,我应该如何从转换函数返回对象?

c++ - 删除 std::tuple 的第一种类型

multithreading - Storm Spouts 是否应该仅使用调用 Spout.nextTuple 的线程发出输出?

c - 返回值显示到屏幕时的函数错误

c++ - 将 2D Char 数组保存到 C++ 文件中