assemblyx86-64sleepevent-loopinstructions

If there is any pausing/sleeping or events in x86 assembly


I am wondering if there is anything at the assembly level in x86-64 that allows you to sleep/wait, such that no instructions are run until the wait is done. I have seen the WAIT and PAUSE instructions, but I'm not sure they're related.

I would imagine it like this:

start:
  wait 123, oninterrupt ; 123 milliseconds
  ; then it will go here after that time
oninterrupt:
  ; ctrl-c pressed, now exit

Likewise, I am wondering if there are event hooks/handlers in x86. So if someone presses CTRL+C, there will be an interrupt event sent to assembly somewhere and you can run your "exit" code on that. I would imagine an event handler could be written in assembly x86 like this:

start:
  int 10, onctrlc ; register handler for made up event
  ; ... more instructions evaluate right after
onctrlc:
  ; control+c pressed, now exit

But I'm not just thinking for CTRL+C, but for any event (which I don't know that much about). I saw this tiny event loop lib in C, not sure if any of that can be done with a simple assembly instruction. Things like keyboard events, socket events, file events, other events I'm not sure what they would be.

Also, this would be run as a regular user on an operating system. But knowing how to do it for privileged users would be nice to know. And also not concerned with how you can do it with linux C functions or syscalls, I understand how to do it like that so far.


Solution

  • The basic instruction to do what you want is HLT. It stops executing instructions until an interrupt is received.

    A newer instruction that is similar is MWAIT. It waits like halt, but it also wakes up when a particular memory location is written (either by a different CPU core or by an I/O device). MWAIT also puts the CPU in a lower power state than halt does. The MONITOR instruction is used to specify the memory location that will cause MWAIT to wake up.

    The other types of events you mentioned are software constructs. The CPU instructions don’t know about keyboards, files, or network devices.

    MWAIT and HLT are privileged instructions. If an application wants to put the CPU to sleep, it generally needs to call the OS, so the OS can schedule some other process, if there is one ready to run.