Sync mechanism for entering sleep mode

Sample code showing how this should be used can be found in the commit description.

May not be correct, but successfully passed several tests.