He finished ninth, ahead of arch rival Jonas Hogh-Christensen from Denmark in tenth, in the Finn class final double points showdown race at Weymouth.
He won Laser class silver at his first Games at Atlanta in 1996 followed by golds at Sydney in 2000 (Laser), Athens in 2004 (Finn) and Beijing in 2008 (Finn).
His Finn victory today sees him eclipse the record of Denmark’s Paul Elvstrom, previously the most successful Olympic sailor ever with four golds from 1948 to 1960.
It is Great Britain's 15th gold medal of the 2012 Games.
After the race Ainslie paid tributes to the thousands of British supporters who had packed the shoreline to cheer him to victory.
While stopping short of announcing his retirement, he said it was extremely unlikely that he would bid for a fifth Olympic gold medal at Rio de Janeiro in Brazil in 2016.
Ainslie said: "It's times like this you are supposed to come out with something clever but I can't think of anything. I am speechless. I am just so glad for everyone who has supported me over the last four years. It has been an amazing Olympics.
"After six races I was in a bit of trouble, thankfully I turned things round and got it right when it counted. This was one of the hardest courses I have raced on and I don't want to do anything like that again.
"I learnt to sail for fun so it's been a long road but I have had a lot of support over the years and I am just so glad to have done it. It's been incredibly hard - there's a huge amount of pressure to perform at a home Games, it's been the hardest couple of weeks of my life but you just have to get on with the job.
"You can never say never but I don't think I can sail one of these again, it's killing my body so I don't think you will see me in Rio.
"But it's the best way to bow out at a home Olympics."