A lot of Scandinavian lects are said to have common vs neuter gender as opposed to masculine vs feminine, since the common gender came about from a merger of the masculine and feminine; likewise, early proto-Indo-European is said to have had animate vs inanimate genders, and only later split the animate gender into masculine vs feminine. So what we call the grammatical genders — or even whether we call them genders at all, as opposed to noun class — is really a pretty arbitrary thing. This being said, though, it's a mistake to think that grammatical gender must reflect some trait of the referent in any case, and it's also a mistake to think that grammatical gender has absolutely nothing to do with social gender: the truth is somewhere in the middle. So you can't blame Welsh having masculine and feminine genders on Anglo-Saxon sexual hierarchies, because all evidence points to the Celtic languages having had masculine and feminine genders the whole time — proto-Celtic also had a neuter gender.
As far as I understand through half-remembering David J Peterson's book on how to conlang good, grammatical gender/class is believed to first come about through grammaticalization of some sort of commonly-used distinguishing word (think analog vs digital clock e.g.). So basically the distinguishing word gets progressively more reduced as it becomes progressively more overused, until it just sort of fuses into the word it's modifying and is reinterpreted as a grammatical affix of some sort. Then sometimes different distinguishing words are reduced or changed so much that they merge into each other as they grammaticalize; or sometimes words end up being caught in one category or another just because they happen to start or end with a certain associated sound, even if it's just a coincidence; or sometimes words just change genders for any number of other arbitrary reasons.
A system of masculine vs feminine gender specifically as far as I understand probably first started in like overused (socially) gendered baby name components and just sort of spiraled out from there. There's also something to be said about like the animacy hierarchy and obviation or whatever, when it comes to the evolution of the neuter gender, but this isn't really my field of expertise anyways. There's even languages like Italian and Romanian where some nouns behave as one gender in the singular and a different gender in the plural. It's a fuck.
Edit: Also, I want to say that I'm a bit bothered by the other comments here since they contain what I identify as mistakes, but I can't exactly say "pop linguistics and its consequences have been a" from my own armchair.