需要在while循环中休息

时间:2013-03-12 08:31:14

标签: c++ loops if-statement

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

所以应该是以下哪一项 - 我只是不知道是否有正确的事情要做。

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;
    }
}

1 个答案:

答案 0 :(得分: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);
    }
}

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