0

我正在编写一个循环,如果队列不为空,则循环将运行,我只是想知道是否需要break在循环末尾包含 a 。基本上每个循环都应该针对队列中的每个元素运行,直到队列为空。

那么它应该是以下哪一个 - 我只是不知道是否有正确的事情要做。

while (1)
{

    /*process message from incoming queue*/
    if (!msgs_inc.empty())
    {
        /*categorise incoming message into global map of outgoing messages*/
        msgInfo current_msg = incMsgClassification(msgs_inc.front());
        msgs_inc.pop();

        clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
    }
}

或者

while (1)
{
    //Sleep(50000);
    //cout << "success" << endl;

    /*process message from incoming queue*/
    if (!msgs_inc.empty())
    {
        /*categorise incoming message into global map of outgoing messages*/
        msgInfo current_msg = incMsgClassification(msgs_inc.front());
        msgs_inc.pop();

        clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
        break;
    }
}
4

1 回答 1

8

你想要做的是更干净地写成..

while (!msgs_inc.empty()) // loop as long as queue still has elements
{    
    /*process message from incoming queue*/
    /*categorise incoming message into global map of outgoing messages*/
    msgInfo current_msg = incMsgClassification(msgs_inc.front());
    msgs_inc.pop();

    clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
}

也许

while(1) {//infinite loop
    while (!msgs_inc.empty()) // loop as long as queue still has elements
    {    
        /*process message from incoming queue*/
        /*categorise incoming message into global map of outgoing messages*/
        msgInfo current_msg = incMsgClassification(msgs_inc.front());
        msgs_inc.pop();

        clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
    }
}

如果此函数在单独的线程上运行,这更相关,并且是在该线程上运行的唯一一段代码。

于 2013-03-12T08:33:42.153 回答