At least 40 people have been killed in an attack on a mosque in Pakistan.

The mosque in the town of Rawalpindi, close to the capital Islamabad, is frequented by military officials.

'They were three. They first opened fire and then blew themselves up,' Rao Iqbal, Rawalpindi police chief, told Reuters.

Witnesses said earlier that attackers hurled grenades then opened fire on the mosque.

The violence will put President Asif Ali Zardari under pressure to do more to neutralise the threat from the stubborn Taliban insurgency.

Pakistan is fighting Taliban fighters blamed for bombings that have killed hundreds of people since an offensive was launched on their stronghold South Waziristan in October.

The president is an increasingly unpopular figure who has been at odds with the all-powerful military, which sets national security policy.

It is the second assault on the area since October, when suspected Taliban gunmen attacked the army compound, killing three hostages and two army commandos.

'Initial information indicates that they were two to three attackers who entered the mosque by scaling a wall,' said senior police official Aslam Tarin.

In outlining his Afghanistan strategy in a speech on Tuesday, US President Barack Obama made a plea to Pakistan to fight the 'cancer' of extremism and said Washington would not tolerate Pakistan allowing its territory to be a safe haven for militants.

That request may be unrealistic in a country where anti-US feelings and suspicions run high.