TinyXml的读取和编辑以及多线程的锁

这篇博客介绍了如何使用TinyXml库在C++中读取和编辑XML文件,特别是针对多线程环境下的锁机制。通过示例展示了如何在多个线程中安全地更新XML文件`mac.xml`,确保数据的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

#include <iostream>

#include <pthread.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <dirent.h>

#include <errno.h>

#include <vector>

#include <algorithm>

#include <unistd.h>

#include "tinyxml/tinyxml.h" //本地下载了tinyxml源码

#include <stdexcept>

#include <map>

#include <fcntl.h>

#include <stdlib.h>

#define MACXML "mac.xml"

using namespace std;

 

static bool usingMacXml = false;

pthread_mutex_t mutexMac = PTHREAD_MUTEX_INITIALIZER;

 

struct mac_data{

    string mac;

    string account;

    string password;

    string status;

};

 

 

void setMacStatus(mac_data m,string status)

{

   pthread_mutex_lock( &mutexMac );

    while(true)

    {

        if(!usingMacXml)

        {

            usingMacXml = true;

 

            TiXmlDocument* macXml = new TiXmlDocument();

            while(!(macXml->LoadFile(MACXML)))

            {

            }

            TiXmlElement* rootElement = macXml->RootElement();  //MacList

            TiXmlElement* macElement = rootElement->FirstChildElement();  //Machine

 

            while ( macElement ) {

                TiXmlElement* nameElement = macElement->FirstChildElement();//获得Machine的Name元素

                TiXmlElement* accountElement = nameElement->NextSiblingElement(); //获得Machine的Password元素

                TiXmlElement* passwordElement = accountElement->NextSiblingElement(); //获得Machine的Account元素

                TiXmlElement* statusElement = passwordElement->NextSiblingElement(); //获得Machine的Status元素

                bool condition = m.mac ==nameElement->GetText() && m.account ==accountElement->GetText() && status !=statusElement->GetText();

                if(condition)

                {

                    statusElement->Clear();

                    TiXmlText * text = new TiXmlText(status );

                    statusElement->LinkEndChild( text );

                    break;

                }

                else

                    cout<<"No match "<<m.mac<<" "<<nameElement->GetText()<< " account:"<<m.account<<" "<<accountElement->GetText()<<" status:" <<m.status<<" " <<statusElement->GetText()<<endl;

 

                cout<<"condition is "<<condition<<endl;

                macElement = macElement->NextSiblingElement();

            }

            macXml->SaveFile(MACXML);

 

            delete macXml;

            usingMacXml = false;

            break;

        }

        else

            system("sleep 1");

    }

    pthread_mutex_unlock(&mutexMac);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值