$$2Mg(s) + O_2(g) → 2MgO(s)$$
This equation tells us that 2 moles of Mg react with 1 mole of O2. First, we need to convert the given mass of Mg (4.0 g) to moles using its molar mass (24.305 g/mol):
$$4.0\text{ g Mg} \times \frac{1\text{ mol Mg}}{24.305\text{ g Mg}} = 0.164\text{ mol Mg}$$
According to the balanced chemical equation, for every 2 moles of Mg, 1 mole of O2 is required. Therefore, the number of moles of oxygen gas needed to react with 0.164 moles of Mg is:
$$0.164\text{ mol Mg} \times \frac{1\text{ mol O}_2}{2\text{ mol Mg}} = 0.082\text{ mol O}_2$$
Hence, 0.082 moles of oxygen gas are required to react with 4.0 g of Mg.