diff --git a/0-limit-crawler/main.go b/0-limit-crawler/main.go index ddadd14..95070f7 100644 --- a/0-limit-crawler/main.go +++ b/0-limit-crawler/main.go @@ -12,11 +12,12 @@ package main import ( "fmt" "sync" + "time" ) // Crawl uses `fetcher` from the `mockfetcher.go` file to imitate a // real crawler. It crawls until the maximum depth has reached. -func Crawl(url string, depth int, wg *sync.WaitGroup) { +func Crawl(url string, depth int, wg *sync.WaitGroup, throttle *time.Ticker) { defer wg.Done() if depth <= 0 { @@ -35,7 +36,8 @@ func Crawl(url string, depth int, wg *sync.WaitGroup) { for _, u := range urls { // Do not remove the `go` keyword, as Crawl() must be // called concurrently - go Crawl(u, depth-1, wg) + <-throttle.C + go Crawl(u, depth-1, wg, throttle) } } @@ -43,6 +45,7 @@ func main() { var wg sync.WaitGroup wg.Add(1) - Crawl("http://golang.org/", 4, &wg) + throttle := time.NewTicker(2 * time.Second) + Crawl("http://golang.org/", 4, &wg, throttle) wg.Wait() } diff --git a/1-producer-consumer/main.go b/1-producer-consumer/main.go index e508e93..a6600f6 100644 --- a/1-producer-consumer/main.go +++ b/1-producer-consumer/main.go @@ -10,22 +10,25 @@ package main import ( "fmt" + "sync" "time" ) -func producer(stream Stream) (tweets []*Tweet) { +func producer(stream Stream, conn chan *Tweet, wg *sync.WaitGroup) { + wg.Done() for { tweet, err := stream.Next() if err == ErrEOF { - return tweets + close(conn) + return } - - tweets = append(tweets, tweet) + conn <- tweet } } -func consumer(tweets []*Tweet) { - for _, t := range tweets { +func consumer(conn chan *Tweet, wg *sync.WaitGroup) { + defer wg.Done() + for t := range conn { if t.IsTalkingAboutGo() { fmt.Println(t.Username, "\ttweets about golang") } else { @@ -38,11 +41,16 @@ func main() { start := time.Now() stream := GetMockStream() + conn := make(chan *Tweet) + var wg sync.WaitGroup + wg.Add(2) // Producer - tweets := producer(stream) + go producer(stream, conn, &wg) // Consumer - consumer(tweets) + go consumer(conn, &wg) + + wg.Wait() fmt.Printf("Process took %s\n", time.Since(start)) } diff --git a/3-limit-service-time/main.go b/3-limit-service-time/main.go index 6a0ebb3..ca20913 100644 --- a/3-limit-service-time/main.go +++ b/3-limit-service-time/main.go @@ -10,6 +10,8 @@ package main +import "time" + // User defines the UserModel. Use this to check whether a User is a // Premium user or not type User struct { @@ -21,8 +23,19 @@ type User struct { // 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 + + timer := time.NewTimer(10 * time.Second) + done := make(chan bool) + go func() { + process() + done <- true + }() + select { + case <-timer.C: + return false + case <-done: + return true + } } func main() {