我有一个xml文件,程序的每个新线程(BHO)都使用相同的Tinyxml文件。
每次在程序中打开一个新窗口时,它都会运行以下代码:
const char * xmlFileName = "C:\\browsarityXml.xml";
TiXmlDocument doc(xmlFileName);
doc.LoadFile();
//some new lines in the xml.. and than save:
doc.SaveFile(xmlFileName);
问题是,在第一个窗口向xml添加新数据并保存后,下一个窗口无法添加到该窗口。虽然下一个可以读取xml中的数据,但它无法写入它。
我想到了两种使其可行的可能性,但我不知道如何实现它们:
对问题的任何帮助或更好的理解都会很棒。 感谢。
答案 0 :(得分:2)
根据评论进行更新(废弃上一个回答):
好的,我没有在TinyXml文档中看到太多,它告诉我们如何打开文档而不受其他线程的限制。
在这种情况下你应该做的只是向TiXmlDocument
声明一个实例并在线程之间共享它。每当线程写入文件时,它将进入一个关键部分,写下需要写入的内容,保存文件,然后退出关键部分。
我没有看到另一种解决方法。
每条评论更新:
由于您使用的是MFC线程,因此您的代码应如下所示:
class SafeTinyXmlDocWrapper
{
private:
static bool m_isAlive = FALSE;
static CCriticalSection m_criticalSection;
char* m_xmlFileName;
TiXmlDocument m_doc;
public:
SafeTinyXmlDocWrapper()
{
m_xmlFileName = "C:\\browsarityXml.xml";
m_doc = TiXmlDocument(m_xmlFileName);
m_doc.LoadFile();
m_isAlive = TRUE;
}
~SafeTinyXmlDocWrapper()
{
CSingleLock lock(&m_criticalSection);
lock.Lock(); // only one thread can lock
m_isAlive = FALSE;
// cleanup and dispose of the document
lock.Unlock();
}
void WriteBatch(BatchJob& job)
{
CSingleLock lock(&m_criticalSection);
lock.Lock(); // only one thread can lock
if(m_isAlive) // extra protection in case the destructor was called
{
// write the batch job to the xml document
// save the xml document
m_doc.SaveFile(m_xmlFileName);
}
lock.Unlock(); // the thread unlocks once it's done
}
}
我现在还没有写过C ++,但它应该大致是你正在寻找的。钟声和口哨花费额外费用:)。