Skip to content

Day15 - User-Space Event Loop and poll()

Lab 1: Blocking read

Test

cat /dev/mygpio

Observe

  • Program blocks until event
  • CPU usage is low

Lab 2: Non-blocking read

Python example

import os

fd = os.open("/dev/mygpio", os.O_RDONLY | os.O_NONBLOCK)

while True:
try:
data = os.read(fd, 128)
print(data)
except BlockingIOError:
pass

Observe

  • CPU usage increases (busy loop)

Lab 3: poll()

import os
import select

fd = os.open("/dev/mygpio", os.O_RDONLY)

p = select.poll()
p.register(fd, select.POLLIN)

print("Waiting for events...")

while True:
events = p.poll()
for fileno, event in events: if event & select.POLLIN: data = os.read(fd, 128) print(data.decode().strip())

Observe

  • No CPU usage when idle
  • Wake only when IRQ occurs

Lab 4: Multiple FDs (optional)

Add stdin:

p.register(0, select.POLLIN)

→ understand multiplexing


Lab 5: epoll (optional advanced)

import select

ep = select.epoll()
ep.register(fd, select.EPOLLIN)

while True:
events = ep.poll()
for fileno, event in events:
data = os.read(fd, 128)
print(data)