When multiple threads should access the same object you must use locking. For your case of a temporary file I would create a class that encapsulates all the necessary operations (including deleting the file in the destructor).
Example (using C library
FILE
object and
QMutex Class | Qt Core 5.5[
^] lock object):
#include <QMutex>
#include <stdio.h>
class TempFile
{
public:
TempFile();
~TempFile();
bool Open(const QString& fileName);
void Close();
int Read(char * data, int size);
int Write(const char * data, int size);
protected:
QString name;
FILE *file;
QMutex mutex;
long pos;
};
#include "TempFile.h"
TempFile::TempFile()
{
file = NULL;
pos = 0;
}
TempFile::~TempFile()
{
bool isOpen = file != NULL;
Close();
if (isOpen)
unlink(QString::toLocal8Bit(name).data());
}
bool TempFile::Open(const QString& fileName)
{
file = fopen(QString::toLocal8Bit(fileName).data(), "w+");
name = fileName;
return file != NULL;
}
void TempFile::Close()
{
if (file)
fclose(file);
file = NULL;
pos = 0;
}
int TempFile::Read(char * data, int size)
{
mutex.lock();
fseek(file, pos, SEEK_SET);
int read = fread(data, 1, size, file);
if (read > 0)
pos += read;
mutex.unlock();
return read;
}
int TempFile::Write(const char * data, int size)
{
mutex.lock();
fseek(file, 0, SEEK_END);
int written = fwrite(data, 1, size, file);
mutex.unlock();
return written;
}