THINK FIRST·CODE LATER

← All labs

Process state machine with validation

Problem

Simulate the seven-state process model and reject invalid transitions.

States: NEW, READY, RUNNING, BLOCKED, TERMINATED, SUSP_READY, SUSP_BLOCKED. Events and the transitions they cause:

Event From → To
admit NEW → READY
dispatch READY → RUNNING (only if no other process is RUNNING — one CPU)
timeout RUNNING → READY
wait RUNNING → BLOCKED
wakeup BLOCKED → READY, or SUSP_BLOCKED → SUSP_READY
exit RUNNING → TERMINATED
suspend READY → SUSP_READY, or BLOCKED → SUSP_BLOCKED
resume SUSP_READY → READY, or SUSP_BLOCKED → BLOCKED

Input: lines create PID (a new process in state NEW) or PID event, until the end of input. For each event print PID: FROM -> TO (event), or PID: invalid event 'event' in state STATE (the state does not change). A dispatch while another process is running prints PID: invalid event 'dispatch' (CPU busy with P). An unknown PID prints unknown process PID. At the end print each process's final state in creation order: Final: P1=READY P2=TERMINATED ... and Invalid events: n.

Input:

create 1
create 2
1 admit
2 admit
1 dispatch
2 dispatch
1 wait
2 dispatch
1 dispatch
1 wakeup
2 exit

Output:

1: NEW -> READY (admit)
2: NEW -> READY (admit)
1: READY -> RUNNING (dispatch)
2: invalid event 'dispatch' (CPU busy with 1)
1: RUNNING -> BLOCKED (wait)
2: READY -> RUNNING (dispatch)
1: invalid event 'dispatch' in state BLOCKED
1: BLOCKED -> READY (wakeup)
2: RUNNING -> TERMINATED (exit)
Final: 1=READY 2=TERMINATED
Invalid events: 2

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.