Gates open automatically if a friendly unit approaches to let them through, and only close again if no unit stands right under the Gate. So, if friendly units (most notably Trade Carts) cause the Gate to open, enemy units can also pass or keep the Gate open on purpose. To prevent that, Gates can be locked so they will not open, even to friendly units. They can be unlocked again at any time.
"Gates were built into walls to allow access to a fortification. Because gates could be the most vulnerable part of a defensive position, extra care was taken to make them strong. A common type of gate was the portcullis, a heavy metal grid that was raised by a winch. The portcullis was in place by grooves in the stonework of the gateway and by its own weight. A long narrow passage, open from above, was usually placed behind the portcullis. Attackers who managed to get past the gate would then remain vulnerable to fire from soldiers in the narrow passage."