00001 // -*- Mode: c++ -*- 00002 #ifndef TFW_H_ 00003 #define TFW_H_ 00004 00005 #include <vector> 00006 using namespace std; 00007 00008 #include <QWaitCondition> 00009 #include <QDateTime> 00010 #include <QString> 00011 #include <QMutex> 00012 00013 #include <fcntl.h> 00014 #include <stdint.h> 00015 00016 #include "mthread.h" 00017 00018 class ThreadedFileWriter; 00019 00020 class TFWWriteThread : public MThread 00021 { 00022 public: 00023 TFWWriteThread(ThreadedFileWriter *p) : MThread("TFWWrite"), m_parent(p) {} 00024 virtual ~TFWWriteThread() { wait(); m_parent = NULL; } 00025 virtual void run(void); 00026 private: 00027 ThreadedFileWriter *m_parent; 00028 }; 00029 00030 class TFWSyncThread : public MThread 00031 { 00032 public: 00033 TFWSyncThread(ThreadedFileWriter *p) : MThread("TFWSync"), m_parent(p) {} 00034 virtual ~TFWSyncThread() { wait(); m_parent = NULL; } 00035 virtual void run(void); 00036 private: 00037 ThreadedFileWriter *m_parent; 00038 }; 00039 00040 class ThreadedFileWriter 00041 { 00042 friend class TFWWriteThread; 00043 friend class TFWSyncThread; 00044 public: 00045 ThreadedFileWriter(const QString &fname, int flags, mode_t mode); 00046 ~ThreadedFileWriter(); 00047 00048 bool Open(void); 00049 bool ReOpen(QString newFilename = ""); 00050 00051 long long Seek(long long pos, int whence); 00052 uint Write(const void *data, uint count); 00053 00054 void SetWriteBufferMinWriteSize(uint newMinSize = kMinWriteSize); 00055 00056 void Sync(void); 00057 void Flush(void); 00058 00059 protected: 00060 void DiskLoop(void); 00061 void SyncLoop(void); 00062 void TrimEmptyBuffers(void); 00063 00064 private: 00065 // file info 00066 QString filename; 00067 int flags; 00068 mode_t mode; 00069 int fd; 00070 00071 // state 00072 bool flush; // protected by buflock 00073 bool in_dtor; // protected by buflock 00074 bool ignore_writes; // protected by buflock 00075 uint tfw_min_write_size; // protected by buflock 00076 uint totalBufferUse; // protected by buflock 00077 00078 // buffers 00079 class TFWBuffer 00080 { 00081 public: 00082 vector<char> data; 00083 QDateTime lastUsed; 00084 }; 00085 mutable QMutex buflock; 00086 QList<TFWBuffer*> writeBuffers; // protected by buflock 00087 QList<TFWBuffer*> emptyBuffers; // protected by buflock 00088 00089 // threads 00090 TFWWriteThread *writeThread; 00091 TFWSyncThread *syncThread; 00092 00093 // wait conditions 00094 QWaitCondition bufferEmpty; 00095 QWaitCondition bufferHasData; 00096 QWaitCondition bufferSyncWait; 00097 00098 // constants 00099 static const uint kMaxBufferSize; 00101 static const uint kMinWriteSize; 00102 }; 00103 00104 #endif
1.6.3