any way to run 2 loops at the same time?

2019-08-28 21:06发布

I want to create a c++ program for a bank queue. Where every 3 minutes a new customer enters the queue. every customer needs 5 minutes for the service. The program print out the information after the first 30 minutes

  • The time of arriving for each customer
  • The time of leaving for each customer
  • How many customers are in the line?
  • Who is the current serving customer?

I wrote the current code:

#include <queue>
#include <ctime>
#include <time.h>
#include <conio.h>
#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
queue <int> inq;
queue <int> inservice;
int z= 1;

for(int i=0; i<=9; i++)
{
    inq.push(z);
    Sleep(180000);
    _strtime_s(hold_time);
    cout<<"Time of arriving for customer number "<<z<<" is: "<<hold_time<<endl;
    z++;
}

do
{
    inservice.push(inq.front());
    Sleep(300000);
    _strtime_s(hold_time);
    cout<<"Time of leaving for customer number "<<z<<" is: "<<hold_time<<endl;
    inq.pop();
}
while(!inq.empty());

cout<<"number of customers waiting : "<<inq.size()<<endl;
cout<<"Customer number "<<inservice.front()<< " is currently serving"<<endl;

return 0;

}

The current code executes line by line; customers will not be moved to service until the queue loop is done. To adjust time, I have to run the two loops at the same time. such that customers enter the queue at the same time other costumers are being served

Any suggestions ?

3条回答
可以哭但决不认输i
2楼-- · 2019-08-28 21:32

To run two loops at the same time, you will need to put them in different threads. Maybe start here to understand threading.

If you want a simulator of bank queuing, you can consider implementing it in Python using SimPy. A bank queue is even one of the examples: SimPy Bank Example

查看更多
来,给爷笑一个
3楼-- · 2019-08-28 21:37

A sophisticated way to approach this would indeed use threading, but if you don't want to do that you should instead loop over time, i.e.

for (int minutes = 1; mintues <= 30; minutes++) {
    // if minutes modulo 3 do something
    // if minutes modulo 5 do something
}

You could loop over seconds, microseconds, whatnot.

查看更多
来,给爷笑一个
4楼-- · 2019-08-28 21:42

You need a more sophisticated code architecture for this. Either naive threading, or an event-dispatch framework that has one busy-loop in main and periodically (based on timers and on events) calls out to other functions as needed.

The most basic yet robust solution you could do would be to have one loop that iterates very quickly (with a very small sleep), repeatedly checking the time to see whether it's time to perform any actions. Those actions will include customers arriving and customers leaving.

Using sleep in other any context is, IMO, usually the sign of a bad design.

查看更多
登录 后发表回答