2

我目前在我的一些代码中遇到了一个非常奇怪的问题。一个变量在其声明后立即损坏并导致访问冲突(基本上指针仍指向同一位置但内存似乎未分配)后似乎很好的变量。我很确定这个问题与多线程有关,但我不知道它是什么,因为我对多线程很陌生。

这是代码:

#include "Firewall.h"
#include <Ws2tcpip.h>

Firewall::Firewall(void)
{
}


Firewall::~Firewall(void)
{
}

void Firewall::parseFile(string filePath)
{
    XMLNode xMainNode=XMLNode::openFileHelper(filePath.c_str(),"firewall");

    // Filtrage
    XMLNode nodeFiltrage = xMainNode.getChildNode("filtrage");
    XMLNode currentNode;

    for(int i=0; i < nodeFiltrage.nChildNode();i++)
    {
        currentNode = nodeFiltrage.getChildNode(i);

        string nom = currentNode.getName();

        if(nom == "permettre")
            mapFiltrage_.insert(pair<int,bool>(atoi(currentNode.getAttribute().lpszValue), true));

        else if(nom == "bloquer")
            mapFiltrage_.insert(pair<int,bool>(atoi(currentNode.getAttribute().lpszValue), false));
    }

    // Redirection

    XMLNode nodeRedirection = xMainNode.getChildNode("redirection");
    XMLNode currentSubNode;

    for(int i = 0; i < nodeRedirection.nChildNode(); i++)
    {
        currentNode = nodeRedirection.getChildNode(i);
        currentSubNode = currentNode.getChildNode("source");

        SourceDestination source((string)currentSubNode.getAttribute("adresse"), atoi(currentSubNode.getAttribute("port")));

        currentSubNode = currentNode.getChildNode("destination");
        SourceDestination destination((string)currentSubNode.getAttribute("adresse"), atoi(currentSubNode.getAttribute("port")));

        mapRedirection_.insert(pair<SourceDestination, SourceDestination>(source,destination)); 

        pair<SourceDestination, SourceDestination> test;
    }


}

void Firewall::initialiser()
{
    std::map<int, bool>::iterator iterFiltrage = mapFiltrage_.begin();
    HANDLE handleThread;

    std::string tempFiltrage = "localhost";
    thread_arg arg;

    // Parcours et lancement des connexions de filtrage
    while(iterFiltrage != mapFiltrage_.end())
    {
        arg.port = (*iterFiltrage).first;
        arg.host = tempFiltrage;
        arg.objRef = this;

        handleThread = CreateThread(NULL, 0, listenThread, &arg, 0, NULL);
        listeThread_.push_back(handleThread);

        iterFiltrage++;
    }

    // Parcours et lancement des connexions de redirection
    std::map<SourceDestination, SourceDestination>::iterator iterRedirection = mapRedirection_.begin();

    while(iterRedirection != mapRedirection_.end())
    {
        // Éviter la duplication inutile des sockets
        if(mapFiltrage_.find((*iterRedirection).first.Port()) == mapFiltrage_.end())
        {
            arg.host =  (*iterRedirection).first.Host();
            arg.port = (*iterRedirection).first.Port();
            arg.objRef = this;

            handleThread = CreateThread(NULL, 0, listenThread, &arg, 0, NULL);
            listeThread_.push_back(handleThread);
        }

        iterRedirection++;
    }
}


DWORD WINAPI Firewall::listenThread(LPVOID lpParam)
{
    thread_arg* temp = (thread_arg*)lpParam;
    Firewall* firewallRef = temp->objRef;

    return firewallRef->runThread(lpParam);
}

DWORD Firewall::runThread( LPVOID lpParam )
{
    thread_arg* infosSocket = (thread_arg*)lpParam;

    // Créer le socket et l'attacher à la source
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);

    if(sock == INVALID_SOCKET)
    {
        cout << "Erreur de creation de socket" << endl;
        return EXIT_FAILURE;
    }

    //Recuperation de l'adresse locale
    hostent *thisHost;
    const char* test = infosSocket->host.c_str();
    thisHost=gethostbyname(test);
    char* ip;
    ip=inet_ntoa(*(struct in_addr*) *thisHost->h_addr_list);

    SOCKADDR_IN sin;
    sin.sin_addr.s_addr = inet_addr(ip);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(infosSocket->port);



    if(bind(sock, (SOCKADDR*)&sin, sizeof(sin)) == SOCKET_ERROR)
    {
        cout << "Erreur de binding" << endl;
        return EXIT_FAILURE;
    }

    // Contexte du client
    SOCKADDR_IN csin;
    SOCKET csock;
    socklen_t crecsize = sizeof(csin);

    listeSocket_.push_back(sock);
    listeSocket_.push_back(csock);

    // Écouter sur le port
    if(listen(sock, 5) == SOCKET_ERROR)
    {
        cout << "Erreur de listen" << endl;
        return EXIT_FAILURE;
    }

    //csock = accept(sock, (SOCKADDR*)&csin, &crecsize);

    return EXIT_SUCCESS;
}

void Firewall::quitter()
{
    // Fermer les sockets
    vector<SOCKET>::iterator iter1 = listeSocket_.begin();

    while(iter1 != listeSocket_.end())
    {
        closesocket((*iter1));
        iter1++;
    }

    // Fermer les threads

    vector<HANDLE>::iterator iter2 = listeThread_.begin();

    while(iter2 != listeThread_.end())
    {
        TerminateThread((*iter2), EXIT_SUCCESS);
        CloseHandle((*iter2));
    }
}

非常感谢。

4

1 回答 1

1

您的问题出在以下代码中:

thread_arg arg;

loop(...)
{
    arg = ...;
    handleThread = CreateThread(..., &arg, ...);
}

此处启动的每个线程都接收到同一个 thread_arg 实例的地址。然后,为了启动下一个线程,您再次在先前启动的线程的脚下修改该实例。作为补救措施,创建一个包含必要参数(主机、端口、this)和线程句柄的结构。将此结构存储在 std::list 中,然后将相应元素的地址传递给 CreateThread()。

您的代码中还有另一个问题,您应该检查返回值。如果您知道已检测到所有明显的错误,那么在某些代码上寻求帮助会更好。为此,使用异常是最简单的。在 CreateThread() 之后,可能应该是 beginthread(),添加以下行:

if(handleThread == NULL)
    throw std::runtime_error("CreateThread() failed");

在第二步中,创建一个从 runtime_error 派生的专用异常类,它包含 win32 错误代码(请参阅 GetLastError())并在异常消息中包含文本错误描述(请参阅 FormatString())。这可能听起来像很多代码都没有,但你只写了一次,你可以在很多地方重用它。

最后,您的 quitter() 有两个问题。第一个是无限循环。假设您在关闭手柄后不需要手柄,请尝试以下操作:

for(; listeThread_.empty(); listeTread_.pop_back())
{
    TerminateThread(listeThread_.back(), EXIT_SUCCESS);
    CloseHandle(listeThread_.back());
}

您也可以将其写为 while 循环,但如果迭代次数基本上是固定的,我个人更喜欢 for 循环。当然,您仍然需要检查 TerminateThread() 和 CloseHandle() 的返回值。第二个问题是 TerminateThread() 是一个坏主意,因为您可能会在完成一半的事情中间终止线程。在网上搜索“终止线程有害”。此时,您所能做的就是使用 WaitForSingleObject() 等待它结束。

于 2013-04-09T05:51:04.430 回答