因此,我正在编写一个程序,该程序在交通信号灯系统上对行驶中的汽车进行分类。它按北,东,南,西对汽车分类,并按顺时针方向移动。我遇到一个问题,在该问题上我执行了goto和对计数器进行重置,以衡量在给定的行驶中可以通过多少辆汽车。
我尝试将goto设置到其他位置,重新安排它如何对向量进行分类并检查索引,还尝试找出计数器重置可能不起作用的地方。该程序在linux服务器上运行,并使用子进程和父进程。
#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
#include <sys/wait.h>
//Jeremy Bayangos - 1646316
//OS Class - Castro - Mon/Wed
//COSC3613
using namespace std;
struct cars
{
string name;
char dr;
int t;
};
bool init(vector<cars> &arr, char direct) {
if (!arr.empty())
for (vector<cars>::size_type i = 0; i < arr.size(); ++i) {
if (arr.at(i).dr == direct) {
return true;
}
} return false;
}
int direct_counter(vector<cars> &arr, char n)
{
int count = 0;
if (!arr.empty())
for (int i = 0; i < arr.size(); ++i) {
if (arr.at(i).dr == n) {
count++;
}
} return count;
}
char direct_bound(char e)
{
if (e == 'E')
{
cout << "Current direction: Eastbound" << endl;
}
if (e == 'S')
{
cout << "Current direction: Southbound" << endl;
}
if (e == 'W')
{
cout << "Current direction: Westbound" << endl;
}
if (e == 'N')
{
cout << "Current direction: Northbound" << endl;
}
}
char direct_shift(char e)
{
if (e == 'N')
{
return 'E';
}
else if (e == 'E')
{
return 'S';
}
else if (e == 'S')
{
return 'W';
}
else if (e == 'W')
{
return 'N';
}
else
{
return '\0';
}
}
int main() {
vector <cars> keeper;
queue <cars> que;
char track; //starting direction
int car_num; //starting car num
string plate;
char dir;
int sec;
cin >> track;
cin >> car_num;
while (cin >> plate >> dir >> sec) //takes the input of plate,
direction and time
{
cars temp;
temp.name = plate;
temp.dr = dir;
temp.t = sec;
keeper.push_back(temp);
}
char curr_dir = track;
int counter = 0;
while (not keeper.empty())
{
for (auto i = 0; i < keeper.size(); i++) {
truckstop:
if (init(keeper, curr_dir))//if directions is inside
vector
{
if (keeper.at(i).dr == curr_dir)// if current
direction its facing is correct
{
if (car_num == 1 or
direct_counter(keeper, curr_dir == 1))
{
que.push(keeper[i]); //pushes
vector at i into queue
keeper.erase(keeper.begin() +
i); // deletes vector at index i
curr_dir =
direct_shift(curr_dir);
counter = 0;
break;
}
else if (car_num > 1) {
que.push(keeper[i]); //pushes
vector at i into queue
keeper.erase(keeper.begin() +
i); // deletes vector at index i
counter++;
if (counter == car_num) {
curr_dir =
direct_shift(curr_dir);
counter = 0;
break;
}
else {
counter = 0;
goto truckstop;
}
}
}
}
else
{
curr_dir = direct_shift(curr_dir);
goto truckstop;
}
}
}
int pid;
char d1 = que.front().dr;
char d2;
while (not que.empty())
{
if (d1 != d2)
{
direct_bound(que.front().dr);
}
if ((pid = fork() == 0))
{
cout << "Car " << que.front().name << " is using the
intersection for " <<
que.front().t << " sec(s)." << endl;
sleep(que.front().t);
exit(0);
}
else
{
d1 = que.front().dr;
wait(0);
que.pop();
if (not que.empty())
{
d2 = que.front().dr;
}
}
}
return 0;
}
答案 0 :(得分:0)
您从父进程和子进程访问“ que”而没有同步,这可能导致不可预测的结果。我建议您首先不使用“ fork”来实现您的逻辑。