我正在开发一个模拟加油站的程序。车站的每辆车都是自己的线程。每辆车必须通过一个位掩码循环检查泵是否打开,如果是,则更新位掩模,填满并通知其他车辆泵已打开。我目前的代码工作正常,但有一些负载平衡问题。理想情况下,所有泵的使用量相同,所有汽车的填充量相同。线程和互斥体
编辑:我的程序基本上需要一些汽车,水泵和一段时间来运行测试。在此期间,汽车会通过不断调用此功能来检查打开的泵。
int Station::fillUp()
{
// loop through the pumps using the bitmask to check if they are available
for (int i = 0; i < pumpsInStation; i++)
{
//Check bitmask to see if pump is open
stationMutex->lock();
if ((freeMask & (1 << i)) == 0)
{
//Turning the bit on
freeMask |= (1 << i);
stationMutex->unlock();
// Sleeps thread for 30ms and increments counts
pumps[i].fillTankUp();
// Turning the bit back off
stationMutex->lock();
freeMask &= ~(1 << i);
stationCondition->notify_one();
stationMutex->unlock();
// Sleep long enough for all cars to have a chance to fill up first.
this_thread::sleep_for(std::chrono::milliseconds((((carsInStation-1) * 30)/pumpsInStation)-30));
return 1;
}
stationMutex->unlock();
}
// If not pumps are available, wait until one becomes available.
stationCondition->wait(std::unique_lock<std::mutex>(*stationMutex));
return -1;
}
我觉得这个问题与我读取它时锁定位掩模有关。我需要在if检查时使用某种互斥或锁定吗?
如果我正确理解代码的方式,它只有一个汽车使用的泵?是对的吗 ? –
@TasosVogiatzoglou不,有多个泵,但不是每个泵对象上都有一个可用的布尔值,站内只有一个int值,用作泵的位掩码。 – user3334986
您在负载平衡中观察到的模式是什么? –