Ghusl is only valid if it was performed after the reason for which it was ordered. Allah the Almighty says :
... And if you are in a state of janabah, then purify yourselves.... (5:6)
Here the Arabic original uses the past form and says:
وإن كنتم جنبا فاطهروا
So "are" is rather "were" and the emphasize is on what happened earlier. As the verb كان always refers to a past (or something which has already started).
This means one first has to have a wet dream or intercourse (legal or illegal) or seemensemen emission ("many" not pre cum "madhy"!) from whatever reason (this includes masturbation) or the menses or child bed bleeding ended before starting to do ghusl. If any or more precisely some of these happens (or more exactly was started) during a ghusl, this ghusl is invalid (because a new cause of ghusl has emerged) and must be restarted.
So in your case your ghusl is only valid if you started it (newly) after masturbation.