I think it could be done fairly easy with 2 keyboard encoders, 2 computers running MAME, and a KVM switch. Take system #2's keyboard encoder and map it to player 2 inputs, then map MAME's player 1 controls on system #2 to be standard MAME player 2 inputs. So when cabinet #2 is in slave mode it's monitor is a clone of cabinet 1 and its keyboard encoder shows up as a 2nd keyboard with player 2 controls mapped, then when it is run independent it the cabinet 2 uses its own copy of MAME, controls and monitor. Most KVM switches have a button combination to make them switch from A to B, something like Shift+F1, this could be programmed into a spare input on the encoder.
It could possibly be done with multiple instances of MAME running on one system, but I think two separate systems would be easiest.