我有一个有2个成员的类:
RequestController {
public:
SendRequest(); // called by multiple threads synchronously
private:
server primary; // This is the primary server
server backup; // This is the back up server.
}我的逻辑很简单:
在SendRequest()中,我想发送请求到主服务器,如果失败,我想发送到备份服务器,如果通过,我想交换主服务器和备份服务器。
问题来了:当我进行交换时,我必须锁定主线程和备份线程(这是多个线程不能同时执行的地方)。实际上,我需要确保在交换时,没有线程正在读取主服务器。如何以有效的方式编写这段代码?我不想锁定整个事情,因为在大多数情况下,主服务器都可以工作,不需要锁定。
我认为这个问题通常是与语言无关的。不管怎样,我用C++标记了它。
发布于 2013-08-03 01:14:18
让我们假设服务器需要花费一些不可忽略的时间来处理请求。然后,如果请求来得足够快,就会出现第二次调用SendRequest的情况,而它正在等待其中一个服务器处理上一个请求。
作为一个设计师,你有两个选择。
在第二种情况下,由于您已经锁定了服务器,因此您可以交换它们,而不会产生任何后果。
对于第一种情况,为什么不执行以下操作:
std::mutex my_mutex;
...
// Select the server
server* selected = NULL;
my_mutex.lock();
selected = &primary;
my_mutex.unlock();
// Let the selected server process the message.
bool success = selected->process();
// If there was a primary failure, see if we can try the backup.
if (!success) {
my_mutex.lock();
if (selected == &primary) {
selected = &backup;
}
my_mutex.unlock();
// Now try again
success = selected->process();
// If the backup was used successfully, swap the primary and backup.
if (success) {
my_mutex.lock();
if (selected == &backup) {
backup = primary;
primary = selected;
}
my_mutex.unlock();
}
}但这可能会有一些问题。例如,假设主节点在第一条消息上失败,但在其余消息上成功。如果SendRequest()被3个不同的线程同时调用,那么你可能会得到以下结果:
备份主线程1-使用primary
如果消息持续以足够快的速度到来,则可以保持这种状态,在这种状态下,您可以不断地交换主和备份。这种情况将在没有挂起消息的瞬间解决,然后设置主和备份,直到再次出现故障。
也许更好的方法是永远不要交换,而是有一个更好的选择方法。例如:
...
// Select the server
server* selected = NULL;
selected = &primary;
if (!primary.last_message_successful) {
// The most recent attempt made with primary was a failure.
if (backup.last_message_successful) {
// The backup is thought to be functioning.
selected = &backup;
}
}
// Let the selected server process the message.
// If successful, process() will set the last_message_successful boolean.
bool success = selected->process();
// If there was a failure, try the other one.
if (!success) {
if (&primary == selected) {
selected = &backup;
} else {
selected = &primary;
}
}
// Try again with the other one.
selected->process();在本例中,锁不是必需的。主节点将一直使用,直到出现故障。则将使用备份。如果同时处理其他消息,可能会导致主消息再次可用,在这种情况下,将使用主消息。否则,备份将一直使用,直到失败。如果两者都失败,则会同时尝试它们,首先是主服务器,然后是备份服务器。
https://stackoverflow.com/questions/18022219
复制相似问题