feat: 进程调度模拟
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type SimRequest struct {
|
||||
Algorithm string `json:"algorithm"`
|
||||
TimeSlice int `json:"timeSlice"`
|
||||
Processes []ProcInput `json:"processes"`
|
||||
}
|
||||
|
||||
type ProcInput struct {
|
||||
Name string `json:"name"`
|
||||
Priority int `json:"priority"`
|
||||
ArrivalTime int `json:"arrivalTime"`
|
||||
NeedTime int `json:"needTime"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
port := "8080"
|
||||
if len(os.Args) > 1 {
|
||||
p, err := strconv.Atoi(os.Args[1])
|
||||
if err == nil && p > 0 && p < 65536 {
|
||||
port = os.Args[1]
|
||||
}
|
||||
}
|
||||
|
||||
fs := http.FileServer(http.Dir("./static"))
|
||||
http.Handle("/", fs)
|
||||
|
||||
http.HandleFunc("/api/simulate", handleSimulate)
|
||||
|
||||
fmt.Printf("进程调度模拟器已启动: http://localhost:%s\n", port)
|
||||
if err := http.ListenAndServe(":"+port, nil); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "服务器启动失败: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSimulate(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req SimRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
procs := make([]*PCB, len(req.Processes))
|
||||
for i, p := range req.Processes {
|
||||
procs[i] = NewPCB(p.Name, p.Priority, p.ArrivalTime, p.NeedTime)
|
||||
}
|
||||
|
||||
var result SimResult
|
||||
if req.Algorithm == "mlfq" {
|
||||
ts := [3]int{1, 2, 4}
|
||||
if req.TimeSlice > 0 {
|
||||
ts[0] = req.TimeSlice
|
||||
ts[1] = req.TimeSlice * 2
|
||||
ts[2] = req.TimeSlice * 4
|
||||
}
|
||||
result = SimulateMLFQ(procs, ts)
|
||||
} else {
|
||||
ts := 2
|
||||
if req.TimeSlice > 0 {
|
||||
ts = req.TimeSlice
|
||||
}
|
||||
result = SimulatePriorityRR(procs, ts)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(result)
|
||||
}
|
||||
Reference in New Issue
Block a user