diff --git a/3-limit-service-time/main.go b/3-limit-service-time/main.go index 6a0ebb3..4899078 100644 --- a/3-limit-service-time/main.go +++ b/3-limit-service-time/main.go @@ -10,19 +10,47 @@ package main +import ( + "sync" + "time" +) + +const MAX_SECONDS = 10 + // User defines the UserModel. Use this to check whether a User is a // Premium user or not type User struct { ID int IsPremium bool TimeUsed int64 // in seconds + mu sync.Mutex } // HandleRequest runs the processes requested by users. Returns false // if process had to be killed func HandleRequest(process func(), u *User) bool { - process() - return true + finished := make(chan bool) + + // unfortunately we won't be able to kill the goroutine. + // So a call to process() may exceeds MAX_SECONDS duration. + go func() { + process() + finished <- true + }() + + select { + case <-finished: + return true + case <-time.After(MAX_SECONDS * time.Second): + if u.IsPremium { + <-finished + return true + } + u.mu.Lock() + u.TimeUsed += MAX_SECONDS + u.mu.Unlock() + return false + } } func main() {